Bluebird:运行承诺返回函数序列

时间:2016-01-11 13:50:25

标签: javascript arrays promise bluebird

运行动态生成的函数序列的最简洁方法是什么,其中每个函数返回一个Promise,必须在下一个函数运行之前解析它?

例如:

axe

Bluebirds // Assume the following 'process' functions are generated elsewhere function process_1 (input) { return new Promise(function (resolve, reject) { resolve(input + '_1'); }); } function process_2 (input) { return new Promise(function (resolve, reject) { resolve(input + '_2'); }); } function process_3 (input) { return new Promise(function (resolve, reject) { resolve(input + '_3'); }); } // We can construct a sequence of these functions, // but each one still needs to be 'configured' with a value // before it can return it's promise. var process = [process_1, process_2, process_3] 上可用的收集方法(例如Promiseall等)似乎处理的集合,而不是承诺生成的集合功能

如果我尝试将序列映射或缩减为一系列承诺而不是函数,那么我就失去了将一个承诺的结果传递给下一个承诺的能力?

2 个答案:

答案 0 :(得分:4)

您可以使用reduce

bluebird.reduce( [process_1, process_2, process_3], function ( input, next ) {                                                                                                                                     
    return next( input );
}, 'INPUT' ).then( function ( result ) { 
    console.log( result );
} );

注意:您还错过了process_2process_3的输入参数,必须添加该参数才能使其生效。

function process_1 (input) {
    return new Promise(function (resolve, reject) {
        resolve(input + '_1');
    });
}

function process_2 ( input ) {
    return new Promise(function (resolve, reject) {
        resolve(input + '_2');
    });
}

function process_3 ( input ) {
    return new Promise(function (resolve, reject) {
        resolve(input + '_3');
    });
}

bluebird.reduce( [process_1, process_2, process_3], function ( input, next ) {
    return next( input );                                                                                                                                                                                          
}, 'INPUT' ).then( function ( result ) {
    console.log( result );
} );

// INPUT_1_2_3

答案 1 :(得分:1)

以下是另一种非蓝鸟特定方式:

var p = arrayOfFns.reduce((p, c) => p.then(c), Promise.resolve('INPUT'));
p.then(console.log);