简体   繁体   English

异步回调循环

[英]Async callback loop

I want to make a loop as follows 我想做一个循环如下

asyncFunction(function(returnedVariable){
    if(returnedVariable < 10 )
        // call asyncFunction() again
    else
        // break/exit
});

Is this possible? 这可能吗?

I can't call it from inside because then 我不能从里面叫它

asyncFunction(function(returnedVariable){
    if(returnedVariable < 10 )
        asyncFunction(function(returnedVariable){
            // ???
        });
    else
        // break/exit
});

EDIT - original answer at bottom. 编辑-底部的原始答案。 after rereading I think you can just do this for your case (although i've never tried referring to a function inside itself like this): 重新阅读后,我认为您可以针对您的情况进行操作(尽管我从未尝试像这样在其内部引用函数):

function asyncFunction(callback){ /* ... do stuff then callback() */ };

function myCallback(returnedVariable){
  if(returnedVariable < 10 ){
    asyncFunction(myCallback);
  } else {
    // break/exit
  }
}

asyncFunction(myCallback);

i'm sure there's a way to do it without a library but for simplicity I always just use caolan/async which works in both node and browser: 我敢肯定有一种无需库就可以做到的方法,但是为了简单起见,我总是只使用caolan / async ,它在节点和浏览器中都可以使用:

var async = require('async');
// for browser, above this script:
// <script src="/path/whatever/async.js" type="text/javascript"></script>

function wrapper(callback){
  var lastReturn = 0;

  function test(){ 
    return lastReturn < 10 
  };

  function iterate(next){
    lastReturn = doSomethingWithPrev(lastReturn);
    next();
  };

  function complete(err){
    if(err){ return callback(err) };
    callback(null, lastReturn);
  };

  async.whilst(test, iterate, complete);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM