I want to respond a JSON object to a path (e.g. /getAbsencesWithNames). I have used the includeNames()
function to read data from a JSON file, process it and save it in a the global JSON object i am trying to respond. The problem is the following command res.end(JSON.stringify(temp, null, "\t"));
executes asynchronously since there is I/O code within includeNames()
function. How can i make this command wait for my function to complete, in other words make it run synchronously?
function includeNames(){
members().then(membersPayload => {
// var counter = 1;
for (var i in respondJson){
var absencesID = respondJson[i].userId;
for (var j in membersPayload){
var membersID = membersPayload[j].userId;
if (absencesID == membersID){
var nameValue = membersPayload[j].name;
JSON.stringify(nameValue);
respondJson[i]["name"] = nameValue;
// console.log(counter + ": " + membersPayload[j].name);
// counter++;
break;
}
}
}
console.log("ITERATION COMPLETED");
}).catch((err) => console.error('error: ' + error.message));
return respondJson;
};
app.get('/getAbsencesWithNames', async (req, res) => {
var temp = await includeNames();
res.end(JSON.stringify(temp, null, "\t"));
console.log("RESPOND SENT");
});
Console output is:
RESPOND SENT
ITERATION COMPLETED
When i was expecting:
ITERATION COMPLETED
RESPOND SENT