.forEach完成后执行回调函数 [英] Executing a callback function after .forEach finishes

查看:1631
本文介绍了.forEach完成后执行回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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完成后执行回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆