简体   繁体   English

循环内的异步功能

[英]Async function inside loop

I'm newer in javascript and trying to execute async function inside loop. 我是javascript的新手,尝试在循环内执行异步功能。 Anyone can explain why loop continuous executing after printing "all done" here is my code 任何人都可以解释为什么在打印“全部完成”后循环连续执行是我的代码

 function asynchFunc(n, loop) { setTimeout(loop, n); } function processItems(items, cb) { (function loop (index) { if (index == items.length) return cb(); console.log(items[index]); asynchFunc(items[index], loop); loop(++index); }(0)); } processItems([1000,2000,3000,4000,5000], function(ret){ console.log('all done'); }); 

There is many problems in your code: 您的代码中有很多问题:

loop call asynchloop wich call loop after n millisecond (with index == undefined). 循环调用asynchloop在n毫秒后调用循环(索引== undefined)。

You're test case is if index == items.length. 您正在测试用例是否索引== items.length。 But when you call loop inside the setTimeout, you pass no parameters so when the setTimeout call loop, your test case failed every time (so the recursivity never ends). 但是,当您在setTimeout内部调用循环时,不会传递任何参数,因此,在setTimeout调用循环时,您的测试用例每次都会失败(因此递归永远不会结束)。

If you want your code works you need to pass index in your asyncFunc function and stop calling loop at the end of the loop function, like this : 如果您想让代码正常工作,则需要在asyncFunc函数中传递索引,并在循环函数的末尾停止调用循环,如下所示:

function asynchFunc(n, loop, index) {
    setTimeout(function() { loop(++index); }, n);
}

function processItems(items, cb) {
(function loop (index) {
  if (index == items.length) return cb();
  console.log(items[index]);
  asynchFunc(items[index], loop, index);
}(0));
}

processItems([1000,2000,3000,4000,5000], function(ret){
console.log('all done');
});

I hope this is clear 我希望这很清楚

The lines: 这些行:

  if (index == items.length) return cb(); 

and

  loop(++index); 

… are called synchronously. ……被同步调用。 You don't want for asynchFunc to finish (and it doesn't accept a callback or return a promise, so unless you edit it, you can't). 您不希望asynchFunc完成(并且它不接受回调或返回承诺,因此,除非您对其进行编辑,否则不能这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM