Dynamic Chaining in Javascript Promises

后端 未结 8 1354
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 20:42

How can I perform dynamic chaining in Javascript Promises, all the time I have seen only hardcoding of the calls for eg., (promise).then(request/funct

8条回答
  •  萌比男神i
    2020-12-08 20:51

    Given an array functions that all return promises, you can use reduce() to run them sequentially:

    var myAsyncFuncs = [
        function (val) {return Promise.resolve(val + 1);},
        function (val) {return Promise.resolve(val + 2);},
        function (val) {return Promise.resolve(val + 3);},
    ];
    
    myAsyncFuncs.reduce(function (prev, curr) {
        return prev.then(curr);
    }, Promise.resolve(1))
    .then(function (result) {
        console.log('RESULT is ' + result);  // prints "RESULT is 7"
    });
    

    The example above uses ES6 Promises but all promise libraries have similar features.

    Also, creating the array of promise returning functions is usually a good candidate for using map(). For example:

    myNewOrmModels.map(function (model) {
        return model.save.bind(model);
    }).reduce(function (prev, curr) {
        return prev.then(curr);
    }, Promise.resolve())
    .then(function (result) {
        console.log('DONE saving');
    });
    

提交回复
热议问题