.forEach完成后执行回调函数

sc28

我正在尝试在forEach循环完成所有迭代之后执行函数。

这个答案提供了一个有趣的解决方案,但我无法使其正常工作。

这是我改编的代码,创建了一个简单的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()功能。

我对粗箭头功能不太熟悉,因此错误可能是由于其用法引起的。

谁能解释该脚本为何不按预期运行?

查理

在这种情况下,更现代的方法是使用诺言

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}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章