javascript Javascript从同一函数内部调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27589093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:40:04  来源:igfitidea点击:

Javascript calling function from inside same function

javascriptasynchronouswhile-loopcallback

提问by Egidi

I have a function that does several DDBB calls, so it is asynchronous.

我有一个执行多个 DDBB 调用的函数,因此它是异步的。

I need to call the function and check a data value (winner) in the JSON object it returns. If it is true i need to call the function again until winner == false.

我需要调用该函数并检查它返回的 JSON 对象中的数据值(获胜者)。如果是真的,我需要再次调用该函数,直到获胜者 == 假。

I can't use while because it is not asynchronous, how can i do this?

我不能使用 while 因为它不是异步的,我该怎么做?

  someFunction(function(result) {
     // if result.winner == true repeat 
  })

回答by dfsq

You can call the same callback function again until condition is true:

您可以再次调用相同的回调函数,直到条件为true

someFunction(function repeat(result) {
    if (result.winner) {
        someFunction(repeat);
    }
});

Check the demo below.

检查下面的演示。

someFunction(function repeat(result) {
    document.body.innerHTML += '<br>' + result.winner;
    if (result.winner) {
        someFunction(repeat);
    }
});

var results = [true, true, true, false];
function someFunction(callback) {
    setTimeout(function() {
        callback({winner: results.shift()});
    }, (Math.random() + 1) * 1000 | 0);
}

回答by YuraA

Have you looked at async.js? It has several control flow async functions. You probably want to look into whilst, doWhilst, until, doUntil:

你看过 async.js 吗?它有几个控制流异步功能。您可能想查看 while、doWhilst、until、doUntil:

https://github.com/caolan/async#whilst

https://github.com/caolan/async#whilst

whilst(test, fn, callback)

Repeatedly call fn, while test returns true. Calls callback when stopped, or an error occurs.

反复调用 fn,而 test 返回 true。停止或发生错误时调用回调。