Node.js: How to run asynchronous code sequentially

前端 未结 6 2034
眼角桃花
眼角桃花 2021-01-03 02:37

I have this chunk of code

User.find({}, function(err, users) {
    for (var i = 0; i < users.length; i++) {
        pseudocode
        Friend.find({
              


        
6条回答
  •  时光说笑
    2021-01-03 03:26

    First lets go a bit more functional

    var users = User.find({});
    
    users.forEach(function (user) {
      var friends = Friend.find({
        user: user._id
      });
      friends.forEach(function (friend) {
          if (user.websiteaccount !== 'None') {
             post(friend, user);
          }
          sendMail(friend, user);
      });
    });
    

    Then lets async that

    async.waterfall([
      async.apply(Users.find, {}),
      function (users, cb) {
        async.each(users, function (user, cb) {
          async.waterfall([
            async.apply(Friends.find, { user, user.id}),
            function (friends, cb) {
              if (user.websiteAccount !== 'None') {
                post(friend, user, function (err, data) {
                  if (err) {
                    cb(err);
                  } else {
                    sendMail(friend, user, cb);
                  }
                });
              } else {
                sendMail(friend, user, cb);
              }
            }
          ], cb);
        });
      }
    ], function (err) {
      if (err) {
        // all the errors in one spot
        throw err;
      }
      console.log('all done');
    });
    

    Also, this is you doing a join, SQL is really good at those.

提交回复
热议问题