Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function after an async function completed in node.js?

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

like image 508
newcomer student Avatar asked Aug 08 '17 14:08

newcomer student


People also ask

How do I run one function after another function?

click(function(){ if (condition == 'true'){ function1(someVariable); function2(someOtherVariable); } else { doThis(someVariable); } });

How do I run async function in node JS?

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.

How do I return a value from async in node?

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.


2 Answers

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();

});
like image 52
Jonas Wilms Avatar answered Oct 28 '22 16:10

Jonas Wilms


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();
});
like image 33
Edmundo Rodrigues Avatar answered Oct 28 '22 15:10

Edmundo Rodrigues