In my controller module I have a function httpAddNewLaunch that invokes on POST request:
async function httpAddNewLaunch(req, res) {
let launch = req.body
addNewLaunch(launch)
console.log(launch)
return res.status(201).json(launch)
}
AddNewLaunch function:
async function addNewLaunch(launch) {
launch.flightNumber = (await launchesDataBase.findOne({})).flightNumber + 1
console.log(launch)
await saveLaunch(launch)
// launches.set(launch.flightNumber, launch)
}
saveLaunch function:
async function saveLaunch(launch) {
await launchesDataBase.findOneAndReplace({
flightNumber: launch.flightNumber
}, launch, {
upsert: true
})
}
When function httpAddNewLaunch invokes, it doesn't wait until other functions that it invokes finish(addNewLaunch(launch) -> saveLaunch(launch)), it's just continuing executing, so when I console.log(launch) after calling addNewLaunch(launch) it logs an object without flightNumber.
But then I add await before addNewLaunch(launch), it appends flightNumber.
Why does it work that way, if async functions are just functions that return a Promise, but they are executing like normal functions, so they should be executed in order they were invoked, but in my case it doesn't wait and just console.logs(launch) without flightNumber?
Can you please explain where am I wrong:)
I suggest reading about how Promises and async/await works. There are a lot of good guides/explanations, which you probably should've gone through before starting to use them.
Basically, JS functions execute statement by statement. The await keyword basically puts this on its head: your current function call will "pause" until the given Promise resolves. And if it rejects, your await promise will throw instead. That's the whole point of an async function: being able to "pause the function call" while await'ing the fulfillment of another promise.
An async function essentially returns a promise. So, when you call addNewLaunch(launch) without await, the promise is resolved/rejected but you are not waiting for the response. Add await to "wait" for the promise to end.
await addNewLaunch(launch);