繁体   English   中英

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

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

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

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

res.render('index', {
    posts: myPosts
});
res.end();

在第一个res.render运行的代码中,之后forEach填充post.author

相反映射到Promises而不是使用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();

});

您可以创建一个promises数组,然后使用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();
});

您可以通过两种方式执行此操作,您可以使用Promise或使用计数方法。

计数方法:

var numComplete = 0;
var done = function() {
    if(numComplete >= myPosts.length) {
        // Code to run once finished
    }
};

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

您可以使用Async之类的第三方库。

例:

import each from 'async/each';

var elements = [1, 2, 3, 4, 5, 6];

each(elements, function(el, next) {
    console.log('Processing element ' + el);
    callAsyncFunction(next); //your async function should accept a callback
}, function(err){
    //this is your ending function. It'll be called after all elements have been processed
    if( err ) {
        console.log('A file failed to process');
    } else {
        console.log('Async processing is finished.');
    }
});

您的代码应如下所示:

each(myPosts, function(post, next) {
    getPostAuthor(post.authorID, function(postAuthor) {
        post.author = postAuthor;
        next()
    });
}, function(err) {
    if (!err) {
        res.render('index', {
            posts: myPosts
        });
        res.end();
    }
});

您可以尝试使用for loop async/await

 const sleep = timeout => new Promise(resolve => setTimeout(() => resolve(), timeout)); const myPosts = [1,2,3]; const fetchPosts = async () => { for (let post_id of myPosts) { await sleep(1000); // simulate fetch post console.log('post:', post_id); } console.log('done!'); }; fetchPosts(); 

使用async.eachOf迭代数组并应用异步函数:

 async.eachOf(myPosts, function(post, it, callback){

    // apply async function on each element
    getPostAuthor(post.authorID, function(postAuthor) {
        post.author = postAuthor;
        return callback();
    });

 }, function(err){
    // final callback when flow is finished
    res.render('index', {
         posts: myPosts
    });
    return res.end();
 });

请参阅异步文档: https//caolan.github.io/async/docs.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM