我需要一个等待异步调用然后继续的循环。就像是:
for ( /* ... */ ) { someFunction(param1, praram2, function(result) { // Okay, for cycle could continue }) } alert("For cycle ended");
我该怎么办?你有什么想法?
如果阻止脚本和浏览器,则无法在JavaScript中混合使用同步和异步。
您需要在此处采用完整的事件驱动方式,幸运的是我们可以将丑陋的东西藏起来。
编辑: 更新了代码。
function asyncLoop(iterations, func, callback) { var index = 0; var done = false; var loop = { next: function() { if (done) { return; } if (index < iterations) { index++; func(loop); } else { done = true; callback(); } }, iteration: function() { return index - 1; }, break: function() { done = true; callback(); } }; loop.next(); return loop; }
这将为我们提供一个异步方法loop,您当然可以进一步修改它,例如使用一个检查循环条件的函数等。
loop
现在进行测试:
function someFunction(a, b, callback) { console.log('Hey doing some stuff!'); callback(); } asyncLoop(10, function(loop) { someFunction(1, 2, function(result) { // log the iteration console.log(loop.iteration()); // Okay, for cycle could continue loop.next(); })}, function(){console.log('cycle ended')} );
并输出:
Hey doing some stuff! 0 Hey doing some stuff! 1 Hey doing some stuff! 2 Hey doing some stuff! 3 Hey doing some stuff! 4 Hey doing some stuff! 5 Hey doing some stuff! 6 Hey doing some stuff! 7 Hey doing some stuff! 8 Hey doing some stuff! 9 cycle ended