【问题标题】:How to resolve a set of promises and values using Bluebird如何使用 Bluebird 解决一组承诺和价值观
【发布时间】:2015-05-11 05:31:24
【问题描述】:

我有一个列表值

xs = [1, 2, 3, 4]

我还有一个异步函数square,它返回传递给它的参数平方的承诺。我想将 my to list 的元素并行传递给我的函数,然后将 Promise 收集到一个数组中并等待它们全部完成。我可以将其表述为 map/reduce 操作。

Promise
.map(xs, function(x) {
        return square(x)
    }
)
.reduce(function(ys, y) {
        return ys.concat(y)
    }, [])

这最终会返回解析的值

[1, 4, 9, 16]

很简单。现在说我想像这样在答案数组中包含原始参数。

[{x:1, y:1}, {x:2, y:4}, {x:3, y:9}, {x:4, y:16}]

现在棘手的部分是我有一个对象列表,每个对象在 reduce 步骤的开头都有一个隐藏在其 y 属性中的承诺。如何编写 Bluebird 代码来执行此 reduce 步骤?

【问题讨论】:

  • 这是相切的,但在您的原始代码中,您实际上并不需要这样做.map(xs, function(x) { return square(x); })square 是一个函数,你可以直接传入:.map(xs, square)

标签: javascript promise bluebird


【解决方案1】:

你不会在reduce 步骤中写这个。将其放在map 步骤中:

Promise.map(xs, function(x) {
    return f(x).then(function(y) {
        return {x:x, y:y};
    });
})

事实上,您根本不需要任何 reduce 步骤,因为 map 确实已经将结果收集到了一个数组中。

当然,您可以将其一分为二,然后将代码扁平化

Promise.map(xs, f).map(function(y, i) {
    return {x:xs[i], y:y};
})

但我不认为xs[i] 的事情好得多。

【讨论】:

    【解决方案2】:

    这是我的写法,我在我的 bluebird 中通过 Babel 使用 ES6 代码。

    import {props, map} from "bluebird";
    
    map(xs, x => props({x, y:square(x)}); // do something with it :)
    

    这使用Promise.props 来等待对象的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-20
      • 2016-07-27
      • 2023-03-24
      • 2022-12-17
      • 2014-09-07
      • 2016-04-10
      • 2021-12-09
      • 1970-01-01
      相关资源
      最近更新 更多