javascript - Node.js Promise.all() 挂起

标签 javascript node.js promise

有点卡在这个上了。与 https://github.com/then/promise 合作在 Node.js 上

exports.count = function ( models, callback ) {
  var promises = [];

  models.forEach(function ( name ) {
    promises.push( countOne( name ) );
  });

  Promise.all( promises ).then(function ( res ) {
    callback( null, res );
  });

  Promise.resolve(promises[0]).then(function (res) {
    console.log('resolved individual with res', res);
  });
};

function countOne ( exampleArg ) {
  return new Promise(function ( resolve, reject ) {
    // It resolves or rejects
  });
}

我也尝试过:

Promise.all( promises.map(function ( it ) { return Promise.resolve(it); }) ).then(function ( res ) {
  callback( null, res );
});

无论哪种方式,Promise.all 都不会触发 then。然而,Promise.resolve 确实给出了适当的响应。

最佳答案

您的某个 promise 没有得到解决,在这种情况下,您需要找出是哪一个。

我认为您正在尝试使用 console.log 来做到这一点。如果您使用 forEach 执行此操作,您可以将日志消息附加到所有 promise 并查看哪一个未解决/拒绝。

或者其中一个 promise 被拒绝,而您没有处理它。

我冒昧地重写了你的代码,试试这样:

exports.count = function (models, callback) {
    var allCounts = models.map(countOne);

    // second parameter is the onRejected handler
    Promise.all(allCounts).then(function (res) {
        callback(null, res);
    }, function (err) {
        callback(err);
    });

    promises[0].then(function (res) {
        console.log('resolved individual with res', res);
    });
};

我留在回调中,但我真的只会返回 promise ,更简单,更干净。

ProTip™:
切换到bluebird promise library ,并将您的实现替换为一行:

exports.count = function (models, callback) {
    Promise.map(models, countOne).nodeify(callback);
}

可能会更快。

关于javascript - Node.js Promise.all() 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25512688/

相关文章:

javascript - 当我使用 Nightmare 时,在页面之间移动并进行抓取

javascript - promise 被拒绝或履行困惑

javascript - 如何选择导航元素内的所有链接

javascript - 将 active_section 类添加到菜单部分

javascript - 如何将高度添加到现有高度?

javascript - 在 Centos 5.5 上安装 Node.JS

node.js - 循环和嵌套 Promise

javascript - 使用 jquery 动态创建模态

javascript - 请求nodejs模块不支持某些url的重定向

javascript - 如何使用 Jest 模拟 https.get