在node.js中完成异步函数后如何运行函数?

new*_*ent 5 javascript asynchronous callback node.js

我想在 forEach循环后运行代码。

myPosts.forEach(function(post) {
    getPostAuthor(post.authorID, function(postAuthor) {
        post.author = postAuthor;
    }
});

res.render('index', {
    posts: myPosts
});
res.end();
Run Code Online (Sandbox Code Playgroud)

在上面的代码中先运行res.render,然后forEach填充post.author

Jon*_*lms 6

而是映射到承诺比用foreach迭代,然后使用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();

});
Run Code Online (Sandbox Code Playgroud)