.forEach完成后执行回调函数

编程入门 行业动态 更新时间:2024-10-24 01:48:20
本文介绍了.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完成后执行回调函数

本文发布于:2023-11-25 04:07:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   函数   完成后   forEach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!