简体   繁体   English

异步forEach函数返回未定义

[英]Asynchronous forEach function returns undefined

I'm trying to build an asynchronous forEach function, but unfortunately it returns the value undefined instead of the content of the array for which I had hoped for. 我正在尝试构建一个异步的forEach函数,但不幸的是,它返回的值是undefined而不是我希望的数组内容。 What am I doing wrong? 我究竟做错了什么?

function asyncforEach(array, cb) {
    array.forEach(function(){
        setTimeout(cb, 0);
    });
}

asyncforEach([1,2,3,4], function(i) {
    console.log(i)
});

Pass the variable ( value ) to the callback, in setTimeout . setTimeout中将变量( value )传递给回调。

 function asyncforEach(array, cb) { array.forEach(function(value){ // value: The current array entry setTimeout(cb, 0, value); // Pass it to the callback when setTimeout invokes it. }); } asyncforEach([1,2,3,4], function(i) { console.log(i) }); 

Any parameters passed to setTimeout after the function and delay parameters, are passed to the callback: functiondelay参数之后传递给setTimeout任何参数都传递给回调:

var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);

You missed to get the item in the forEach function parameter and pass the item into the setTimeout , Also call the cb function with passed array item into it. 您错过了在forEach函数参数中获取该item并将其传递给setTimeout ,还调用了带有传递的数组项的cb函数。 This will force the cb function to be called inside the arrow function, when the time will be out. 时间到后,这将强制在箭头函数内部调用cb函数。

 function asyncforEach(array, cb) { array.forEach(function(i) { //-----------------^--- setTimeout( () => cb(i), 0); //----------^^^^^^^^^^^---- }); } asyncforEach([1,2,3,4], function(i) { console.log(i) }); 

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

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