Dynamic Chaining in Javascript Promises

后端 未结 8 1297
伪装坚强ぢ
伪装坚强ぢ 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条回答
  • 2020-12-08 21:08

    This solution based on usage promises of introduced in the EcmaScript 6 (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), so before use it see table browser`s support https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility

    Code

    var f1 = function(){
        for (var i = 0; i < 800000000; i++) {}
        console.log('Function1 is done');
    }
    var f2 = function(){
        for (var i = 0; i < 800000000; i++) {}
        console.log('Function2 is done');
    }
    var f3 = function(){
        for (var i = 0; i < 800000000; i++) {}
        console.log('Function3 is done');
    }
    var f4 = function(){
        for (var i = 0; i < 800000000; i++) {}
        console.log('Function4 is done');
    }
    
    
    callbacks = function(){
    
        // copy passed arguments
        var callbacks = arguments;
    
        // create array functions
        var callbacks = Object.keys(callbacks).map(function(el){ return callbacks[el] });
    
        var now = Date.now();
    
        callbacks.reduce(function(previousPromise, currentFunc){
            return previousPromise.then(
                function(){
                    currentFunc();
                    var seconds = (Date.now() - now) / 1000;
                    console.log('Gone', seconds, 'seconds');
                }
            )
        }, Promise.resolve());
    }
    
    callbacks(f1, f2, f3, f4);
    

    Result in Chrome console (values seconds will be different):

    Function1 is done
    Gone 1.147 seconds
    Function2 is done
    Gone 2.249 seconds
    Function3 is done
    Gone 3.35 seconds
    Function4 is done
    Gone 4.47 seconds
    

    Notes:

    1. It is does not work if a function contains a timer (for this problem I try also jQuery`s $Callbacks, $.Ajax and $.When but it not help. The only decision, what I found, usage resolve() in callback of a timer, but it is not acceptable if you have completed functions.).
    2. Testing environment

    $ google-chrome --version
    Google Chrome 53.0.2785.116
    
    0 讨论(0)
  • 2020-12-08 21:09

    This is ES7 way.

    Let's say you have multiple promises defined in an array.

      var funcs = [
        _ => new Promise(res => setTimeout(_ => res("1"), 1000)),
        _ => new Promise(res => setTimeout(_ => res("2"), 1000))
      }
    

    And you want to call like this.

     chainPromises(funcs).then(result => console.log(result));
    

    You can use async and await for this purpose.

      async function chainPromises(promises) {
        for (let promise of promises) {  // must be for (.. of ..)
          await promise();
        }
      }
    

    This will execute the given functions sequentially(one by one), not in parallel. The parameter promises is an array of functions, which return Promise.

    Plunker: http://plnkr.co/edit/UP0rhD?p=preview

    0 讨论(0)
提交回复
热议问题