如果阻止脚本和浏览器,则无法在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,您当然可以进一步修改它,例如使用一个检查循环条件的函数等。
现在进行测试:
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!0Hey doing some stuff!1Hey doing some stuff!2Hey doing some stuff!3Hey doing some stuff!4Hey doing some stuff!5Hey doing some stuff!6Hey doing some stuff!7Hey doing some stuff!8Hey doing some stuff!9cycle ended
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)