gpt4 book ai didi

jquery - NodeJS 循环等待回调

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:17 25 4
gpt4 key购买 nike

如何在 for 循环中等待,直到收到回调,然后继续 for 循环?

这是我的循环:

for(var i = 0; i < offer.items_to_receive.length; i++) {
console.log("Waiting for callback...");
doSomething(function(data) {
console.log("Got data from callback! " + data);
});
console.log("Continue for loop now.");
}

感谢您的投入!

最佳答案

如果调用的方法是异步的,您可能无法使用循环,而是可以使用基于递归的解决方案,例如

function x(items, i) {
i = i || 0;
if (i >= items.length) {
return
}
snippet.log("Waiting for callback..." + i);
doSomething(function(data) {
snippet.log("Got data from callback! " + data);

if (i == items.length - 1) {
snippet.log("completed");
} else {
x(items, i + 1)
}
});
}

// a sample implementation of asynchronous method
var counter = 0;
function doSomething(cb) {
setTimeout(cb.bind(window, counter++), 100)
}

x([1, 2, 3, 4])
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于jquery - NodeJS 循环等待回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557043/

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