蓝鸟:获取each()的结果 [英] Bluebird: getting the results of each()

查看:47
本文介绍了蓝鸟:获取each()的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 .each(),这是我不了解的地方.该函数返回一个promise,该promise将产生原始数组,而不是回调中的结果数组.那你如何得到结果呢? .map()不是我想要的,因为元素需要按顺序处理.

Here's something I don't understand about .each(). The function returns a promise that yields the original array instead of an array of results from the callback. How you get the results then? .map() isn't what I'm looking for since the elements need to be processed in order.

var input = [1, 2, 3];
return promise.each(input, causeSideEffect).then(function() {
    /* return true if any side effect occurred */
});

在示例中, causeSideEffect()返回一个布尔值的promise,表明它是否做了任何事情.

In the example, causeSideEffect() returns a promise of a boolean, indicating whether it did anything.

产生3.0版行为的垫片

A shim that yield the version 3.0 behavior

var promise = require('bluebird');

var testInput = [ 1 ];
promise.each(testInput, function(){}).then(function(results) {
    if (results[0] === 1) {
        var originalFunction = promise.each;
        promise.each = function(array, callback) {
            var results = [];
            var closure = function(item, index, length) {
                return promise.resolve(callback(item, index, length)).then(results.push.bind(results));
            };
            return originalFunction(array, closure).return(results);
        }
    }
});

推荐答案

我们同意您的意见.实际上,我们非常同意您的观点,以至于这种行为在3.0中有所改变(3.0将返回修改后的数组).

We agree with you. In fact we agree with you so much that this behaviour changes in 3.0 (where 3.0 will return the modified array).

基本上,预计不会以这种方式使用 .each -预计人们只会将 .each 用于副作用,而不是用于他们会做的事情将 .map 用于.

Basically, .each was not anticipated to be used this way - it was expected that people will use .each only for side effects and not for things they'd use .map for.

在此之前,您可以自己进行累积:

Until then, you can either do the accumulation yourself:

var input = [1, 2, 3], result = [];
return promise.each(input, causeSideEffect).then(function() {
    result.push(modificationHappened); // true or false
}).then(function(){
    // access result
}); 

或使用 .reduce 并将结果累加到一个数组中(文档中的示例).

Or use .reduce and accumulate the result into an array (Example in the docs).

这篇关于蓝鸟:获取each()的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆