Asynchronous for cycle in JavaScript

前端 未结 13 1248
温柔的废话
温柔的废话 2020-11-22 11:37

I need a loop that waits for an async call before continuing. Something like:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    //         


        
13条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:46

    I needed to call some asynchronous function X times, each iteration must have happened after the previous one was done, so I wrote a litte library that can be used like this:

    // https://codepen.io/anon/pen/MOvxaX?editors=0012
    var loop = AsyncLoop(function(iteration, value){
      console.log("Loop called with iteration and value set to: ", iteration, value);
    
      var random = Math.random()*500;
    
      if(random < 200)
        return false;
    
      return new Promise(function(resolve){
        setTimeout(resolve.bind(null, random), random);
      });
    })
    .finished(function(){
      console.log("Loop has ended");
    });
    

    Each time user defined loop function is called, it has two arguments, iteration index and previous call return value.

    This is an example of output:

    "Loop called with iteration and value set to: " 0 null
    "Loop called with iteration and value set to: " 1 496.4137048207333
    "Loop called with iteration and value set to: " 2 259.6020382449663
    "Loop called with iteration and value set to: " 3 485.5400568702862
    "Loop has ended"
    

提交回复
热议问题