chaining nested promises in a loop

前端 未结 1 1905
予麋鹿
予麋鹿 2020-12-19 06:31

I am kind of new to promises and are stuck on the following exercise.

I have an array of values and I want to execute an async call on each one. In the callback, I w

相关标签:
1条回答
  • 2020-12-19 06:36

    You don't need the deferred, that's the deferred anti pattern you have there since promises chain.

    Also, you have to return a promise from a .then handler if you want it to wait for it to resolve.

    You can simply use a for loop:

    function do(val) {
    
      var q = Q();
      for(var i = 0; i < val; i++){
        q = q.then(asyncCall.bind(null,i))
             .then(console.log.bind(console))
             .then(console.log.bind(console,"x"));
      }
    
      return q; // in case you want to chain
    }
    

    fiddle.

    Note: Bind just fixates the value for the function call. In this case since the first param (the this value) is null it acts like function(fn,arg){ return function(arg){ return fn(arg); }} that is, it translates a function call to a "partial application" - for more info see the MDN docs.

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