javascript - forEach 的简单 promise

标签 javascript node.js mongoose promise q

我正在尝试使用 Promise 来等待异步 forEach:

var forEachMatch = function(matches) {
    var deferred = Q.defer();
    matches.forEach(function(match) {
        var messages = Message.find({'matchid': match._id}, function(err,messages) {
            if(err)
                console.log(err);
            else
                console.log(match._id);
        });
    });
    return deferred.promise;
};

在这里使用:

forEachMatch(matches, function() {
    console.log("DONE");
    res.status(200).json({
        bob,
        matches: matches,
    });
});

我的控制台输出如下:所有 match._id 都已打印,但 DONE 从未打印。

有什么办法可以解决吗?我从 node 和 promises 开始,所以我当然忘记了一些东西,但我没有看到什么。

感谢您的任何回答。

编辑

最终的解决方案,感谢 Alexander Mac:

var forEachMatch = function(matches) {
  var promises = matches.map(match => {
    return Message
    .find({'matchid': match._id})
    .populate({
      path: 'fromUser toUser',
      select: 'id firstname'
    })
    .then(messages => [match, messages])
    .catch(err => {
      console.log("Error in forEachMatch");
      return [match, null];
    });
  });
  return Q.all(promises);
}

forEachMatch(matches)
  .then(messagesByMatch => {
    res.status(200).json({
      user,
      messagesByMatch: messagesByMatch
    });
  });

最佳答案

在您的情况下,使用 Q.all 可以更好地匹配,它接受 promise 或值的数组:

var forEachMatch = function(matches) {
  var promises = matches.map(match => {
    return Message
      .find({'matchid': match._id})
      .then(messages => [match, messages]);
  });
  return Q.all(promises);
}

forEachMatch(matches)
  .then(results => {
    console.log("DONE", results);
    res.status(200).json({
      bob,
      matches: matches,
  });
});

https://github.com/kriskowal/q/wiki/API-Reference#promiseall

关于javascript - forEach 的简单 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859382/

相关文章:

javascript - 在 Internet Explorer 中查看 localStorage - 无法获取名称/值对

node.js - Node.js 中的 MVC 对于开发 Restful api 重要吗?

javascript - Mongoose 在坐标上抛出错误值

node.js - Mongoose,查找,返回特定属性

javascript - 需要更智能的 jQuery 表排序功能

javascript - 将数字数组从 ajax 传递到 Controller

node.js - 启用 CORS - Node.js + React/Redux + Axios 部署在 Heroku 上

node.js - NodeJS 导出未在外部 JS 文件中定义

javascript - 如何在 MongoDB (Mongoose) 中更新和更新插入文档。 NodeJS

javascript - 在完成 Rxjs Observable 之前,如何等待 subscribe 中定义的异步方法?