我正在尝试在forEach循环完成所有迭代之后执行函数.
I'm trying to execute a function after a forEach loop has completed all iterations.
此答案提供了一个有趣的解决方案,但我无法使其正常工作.
This answer provides an interesting solution, but I can't get it to work.
这是我修改的代码,创建了一个简单的asyncFunction().
Here's the code I adapted, creating a simple asyncFunction().
function callback () { console.log('all done'); } function asyncFunction(item) { console.log("in async function, item is " + item) } var itemsProcessed = 0; [1, 2, 3].forEach((item, index, array) => { asyncFunction(item, () => { itemsProcessed++; console.log("in callback area, itemsProcessed is " + itemsProcessed ) if(itemsProcessed === array.length) { callback(); } }); });在此 JSfiddle 中可见,脚本正确执行了异步功能,但未能输入递增itemsProcessed并应触发callback()功能的部分.
As visible in this JSfiddle, the script correctly executes the async function, but fails to enter the part which increments itemsProcessed and should trigger the callback() function.
我对粗箭头功能不太熟悉,因此错误可能是由于其用法引起的.
I'm not too familiar with the fat arrow functions, so maybe the error comes from their usage.
任何人都可以解释为什么脚本无法按预期方式运行吗?
Can anyone explain why the script isn't behaving as expected?
推荐答案在这种情况下,更现代的方法是使用promises
This is a case where the more modern approach is to use promises
function asyncFunction(item) { // return a promise return new Promise((resolve, reject) => { setTimeout(() => { console.log("in async function, item is " + item) // resolve promise when data is ready resolve(item) }, Math.random()*2000)// random delay to stagger order of returns }) } // create array of promises let promiseArray = [1, 2, 3].map(asyncFunction); // runs when all promises are resolved Promise.all(promiseArray).then(results => { console.log('all done') // results array will be in same order as original array console.log('results are: ', results) })
.as-console-wrapper {max-height: 100%!important;top:0}
更多推荐
.forEach完成后执行回调函数
发布评论