javascript - 如何使用 Bluebird 解决一组 promise 和值(value)观

标签 javascript promise bluebird

我有一个列表值

xs = [1, 2, 3, 4]

我还有一个异步函数 square,它返回传递给它的参数的平方的 promise 。我想将 my to list 的元素并行传递给我的函数,然后将 promises 收集到一个数组中并等待它们全部完成。我可以将其表述为 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 属性中都有一个 promise 。如何编写 Bluebird 代码来执行此减少步骤?

最佳答案

你不会在 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] 会更好。

关于javascript - 如何使用 Bluebird 解决一组 promise 和值(value)观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156292/

相关文章:

javascript - 错误 TypeError : Cannot read property '1' of null at Object. eval [作为 updateDirectives]

javascript - 如何在 javascript 中将项目转换为键/值对对象?

angular - 尝试使用已损坏的 View : detectChanges event though the view is detached

typescript - 在 sequelize db 操作后返回 bluebird promise

javascript - 简单的 jQuery 切换到 $ ("html, body").css( {"overflow": "hidden"}); when opened and then switch to "scroll" when closed

javascript - 是否有谷歌支持的方法来 stub gapi.client JS 库?

javascript - 我可以依赖非链式后续 promise 订单吗?

javascript - 使用 Promises 和 Spies 进行单元测试

javascript - 组织 promise 代码

javascript - Bluebird 创建新用户