gpt4 book ai didi

javascript - 为什么计数器变量没有递减?

转载 作者:行者123 更新时间:2023-12-03 04:47:46 24 4
gpt4 key购买 nike

我正在尝试等待所有回电完成。然而,计数器并没有减少。我该如何解决这个问题?

var counter = json.length;

for(i=0;i<json.length;i++){
FB.api("url",function(response){
doSomething(response);
counter = counter - 1;
});
}

while(counter>0){
alert(counter);
}

在上面的代码中,计数器值与 json.length 保持相同。

最佳答案

问题是......你永远不会让 FB.api 运行,因为你的同步 while 循环占用了所有资源

一个简单的方法如下

var counter = json.length;

for (i=0;i<json.length;i++){
FB.api("url",function(response){
doSomething(response);
counter = counter - 1;
if(counter == 0) {
allDone();
}
});
}

其中 allDone 是在所有 FB.api 完成后运行的函数

现代方法可能会使用 Promise - 也许像这样

Promise.all(json.map(function(item) {
return new Promise(function(resolve, reject) {
FB.api("url",function(response){
doSomething(response);
resolve(response);
});
});
})).then(function(results) {
// all done at this point, results is an array of responses from above
});

或者,正如@Bergi 指出的

Promise.all(json.map(item => 
new Promise(resolve =>
FB.api("url", resolve)
)
.then(doSomething)
))
.then(function(results) {
// all done at this point, results is an array of responses from above
});

(此处为 ES5 版本)

Promise.all(json.map(function(item) {
return new Promise(function(resolve, reject) {
FB.api("url", resolve);
}).then(doSomething);
})).then(function(results) {
// all done at this point, results is an array of responses from above
});

但是,这是假设 FB.api 中的回调仅获得一个参数 - 即发生错误时该怎么办?

关于javascript - 为什么计数器变量没有递减?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com