loops - JavaScript: Perform a chain of promises synchronously -


i have request promises need perform on loop, like:

var ids = [1,2,3]; dopromise(1).then(function(){   dopromise(2).then(function(){     dopromise(3);   } }) 

the problem never know how many elements in array, need dynamic pattern. possible mix sync , async worlds, 1 request active @ moment (sequence being not important)?

a classic way iterate on array sequentually, calling async operation on each array element using .reduce() , chaining initial promise shown below:

the problem never know how many elements in array, need dynamic pattern.

you can use chaining of promises sequence them 1 after. this, useful use .reduce() iterate array since offers right type of iteration keeps track of accumulated value (a promise in case) 1 iterates array. make array iteration scheme work using variables, lines .reduce():

var ids = [1,2,3,4,5,6,7]; ids.reduce(function(p, item) {     return p.then(function() {         return dopromise(item);     }); }, promise.resolve()).then(function(results) {     // done here array of results }); 

this passes resolved promise ids.reduce() head of promise chain. then, .then() on promise , returns new promise each item in array (via .reduce() callback). final result of .reduce() call promise which, when resolved means entire chain done.

the key understanding remember p.then() returns new promise keep calling .then() on each new promise , return promise each operation in each .then() handler. has effect of chaining promises 1 sequential chain.

is possible mix sync , async worlds, 1 request active @ moment (sequence being not important)?

i'm not sure mean "mix sync , async worlds". way make sure 1 request ever in-flight @ time sequence them 1 after other next 1 starts when prior 1 finishes. happens guarantee execution order though isn't important in case, by-product of making sure 1 in-flight @ time.

and, here's working snippet:

function log(msg) {      var d = document.createelement("div");      d.textcontent = msg;      document.body.appendchild(d);  }    function dopromise(x) {      return new promise(function(resolve) {          settimeout(function() {              log(x);              resolve(x);          }, math.floor(math.random() * 1000));      });  }    var ids = [1,2,3,4,5,6,7];  ids.reduce(function(p, item) {      return p.then(function() {          return dopromise(item);      });  }, promise.resolve()).then(function() {      // done here      log("all done");  });


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -