【问题标题】:How can I sequentially chain promises and get result when all finished using bluebirdjs?全部使用 bluebirdjs 完成后,如何按顺序链接 promise 并获得结果?
【发布时间】:2017-08-30 19:24:53
【问题描述】:

here 已经提出了类似的问题,但我很感兴趣,当所有承诺完成时,如何获得结果。

在我的代码中,我正在将文件安装到设备上 - 这需要按顺序完成,并且 install 会创建一个承诺。

受上述示例和example from BluebirdJS documentation 的启发,我提供了以下代码:

  Promise.each(files, function(file, index){
    self.adbClient.install(device, file.path)
    .then(function() {
      console.log('%s installed on device %s', file.name, device)
    })
    .catch(function(err) {
      console.error('Something went wrong when installing %s on %s: '+  err.stack, file.name, device)
    })
  }).then(function() { console.log("All done"); })
  .catch(function(err) { console.log("Argh, broken: " + err.message); })

执行后我得到:

All done
first-file.apk installed on device LGV400d1d1a81d
second-file.apk installed on device LGV400d1d1a81d

如何在所有安装完成后收到All done消息?

【问题讨论】:

    标签: javascript parallel-processing promise bluebird es6-promise


    【解决方案1】:

    根据正确文档http://bluebirdjs.com/docs/api/promise.each.html -

    如果迭代器函数返回一个 promise 或 thenable,则在继续下一次迭代之前等待 promise 的结果

    所以,添加return的简单案例如下

     Promise.each(files, function(file, index){
        return self.adbClient.install(device, file.path)
     // ^^^^^^
     // rest of your code
    

    【讨论】:

    • 非常感谢,这是缺少的退货声明 :-)
    • @karlitos - 问题可能是因为您遵循“错误”示例:p
    猜你喜欢
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2020-01-07
    • 2016-08-23
    • 2019-04-07
    • 2021-01-13
    相关资源
    最近更新 更多