I am calling an asynchronous function which fetches data and subsequently modifies it from another asynchronous function. The latter, however, does not wait until the data was modified in the function called. Currently it is only possible to return the data not anything handled inside the called function since the inside return is not waited for. I tried to async await for the called function but this did not work.
This is the initial call of the function
exports.addRequest = async (req, res) => {
const requestResult = await RequestsModel.addRequestData(req.params.test)
return res.send(requestResult);
};
And this is the function called
exports.addRequestData = async (test) => {
await Requests.findById(requestId)
.then((requestData) =>{
//(01)
if (requestData[type].filter(req => req[compareId] === requestDataObj[compareId]).length !== 0) return "exists";
if (requestData[complementaryType].filter(req => req[complementaryCompareId] === requestDataObj[complementaryCompareId]).length !== 0) return "exists_complementary";
//(02)
requestData[type].push(requestDataObj);
return requestData.save();
}, (err) => {
return err;
});
};
I remove the parameters since they work fine. The only scenario where I return data is when I return the entire lower mongoose function body. For the promise and data handling the upper function does not seem to wait.
Any help is highly appreciated since I just started working with nodejs and asynchronous functions.
Thanks Jakob
.addRequestData()so that it takes advantage ofasyncandawait. Currently, the function does not return anything. Mixingasync/awaitwith.then()is usually a sign that something is wrong..then(), assign the returned value of theawaitin that function to a variable. Then the code in the.then()moves directly intoaddRequestData(). Then thereturnstatement returns back to the calling function. Now, I'm not sure what that.save()does; if it's alsoasyncyou'd want to return the result ofawaiton that call.requestData[type].push(requestDataObj);<-- where is requestDataObj defined?