I am doing a hobby project in NodeJS and Express, but I am overwhelmed by dealing with asynchronous calls. I have encountered a bug that I would like to bounce with the community.
I currently have this layout using Express to which I am sending post requests to.
Express (backend)
app.post("/", async (req, res) => {
const createDocument = (args1) => {
// declare some variables ...
// for loop ...
// (quite fast)
loadFile(args2, async () => {
// upload a file (quite slow)
await upload(file, filePath)
//send post request to third party (quite fast)
let res = await axios.post(url, data, {
headers: {
'X-Auth-Token': KEY
}
}).then(res => console.log('success')).catch(error => console.log('failure'))
})
}
const args1 = "someargs"
await new Promise(resolve => setTimeout(resolve, 2000))
await createDocument(args1)
res.end()
})
React (frontend)
const saveDocButtonClicked = useCallback(async (event) => {
// do some stuff ...
await axios.post('/', {
headers: {
'Content-Type': 'application/json'
},
jsonData
}).then(res => console.log('Data sent')).catch(err => console.log(err.data))
// do some other stuff ...
}
I want the React app to wait, and not proceed before getting a proper response from the API call to the Express backend.
And I want the Express app to give a proper response only when it has performed all of its tasks.
This has worked fine so far for smaller files, but as they increase in size, they no longer get saved / stored in the database.
The key difference I noticed is that in these bad cases, the strings success or failure which should come from this piece of code in the Express backend; .then(res => console.log('success')).catch(error => console.log('failure')) no longer gets outputted. So somewhere the asynchronous events are probably jumping the gun.
I am sure that I have made tons of mistakes, please feel free to point them out, I would love to learn this, I am such a freshman on asynchronous calls.
createDocument, You should return the promise from that function which would resolve wheneverloadFilecompletes. Hope that helps