I’m trying to make facebook api requests in a for loop using request module in nodejs. But I need to make the loop and request calls synchronous. What am I doing wrong?
async function sendRequestAsync(sender, messageData) {
await request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs: {access_token: PAGE_ACCESS_TOKEN},
method: "POST",
json: {
recipient: {id: sender},
message: messageData
}
});
}
function sendFoods (sender, results) {
results.forEach(async result => {
await request.sendRequestasync(sender, {text: result.cat});
await request.sendRequestasync(sender, result.data);
console.log(result);
});
}
2
Answers
Your sendRequestAsync function should just return the promise directly from the request call rather than awaiting it. Await is really just syntactic sugar for .then ().
In ES8 Async/Await the script waits for resolving a promise before it continues the execution.
Try my live example