Asynchronous for cycle in JavaScript

前端 未结 13 1234
温柔的废话
温柔的废话 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:51

    Given an asynchronous worker function someFunction that will call back a result function with a result argument saying whether or not the loop should continue:

    // having:
    // function someFunction(param1, praram2, resultfunc))
    // function done() { alert("For cycle ended"); }
    
    (function(f){ f(f) })(function(f){
      someFunction("param1", "praram2", function(result){
        if (result)
          f(f); // loop continues
        else
          done(); // loop ends
      });
    })
    

    In order to check whether or not to end the loop, the worker function someFunction can forward the result function to other asynchronous operations. Also, the whole expression can be encapsulated into an asynchronous function by taking a function done as callback.

提交回复
热议问题