I want to run a code after my async forEach loop.
myPosts.forEach(function(post) {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
}
});
res.render('index', {
posts: myPosts
});
res.end();
in code above first res.render runs and after that forEach fills the post.author
click(function(){ if (condition == 'true'){ function1(someVariable); function2(someOtherVariable); } else { doThis(someVariable); } });
The asynchronous function can be written in Node. js using 'async' preceding the function name. The asynchronous function returns implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event-loop.
Async functions return a Promise by default, so you can rewrite any callback based function to use Promises, then await their resolution. You can use the util. promisify function in Node. js to turn callback-based functions to return a Promise-based ones.
Rather map to Promises than iterating with forEach, then use Promise.all:
Promise.all(
myPosts.map(function(post) {
return new Promise(function(res){
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
res(postAuthor);
});
});
})
).then(function(authors){
res.render('index', {
posts: myPosts
});
res.end();
});
You can create an array of promises, then listen for all completions using Promise.all
.
const promises = [];
myPosts.forEach(function(post) {
const promise = new Promise((resolve) => {
getPostAuthor(post.authorID, function(postAuthor) {
post.author = postAuthor;
resolve(); // complete the current promise
}
});
promises.push(promise);
});
Promise.all(promises).then(() => {
res.render('index', {
posts: myPosts
});
res.end();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With