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:)