lodash的forEach和[].forEach不支持await, forEach 只支持同步代码。
解决方法1:使用 for...of
解决方法2:使用 for循环
解决方法3:让orEach支持async await
forEach 在正常情况像下面这么写肯定是做不到同步的,程序不会等一个循环中的异步完成再进行下一个循环。原因很明显,在上面的模拟中,while 循环只是简单执行了 callback,所以尽管 callback 内使用了 await ,也只是影响到 callback 内部。
arr.myforeach(async v => {
await fetch(v);
});
要支持上面这种写法,只要稍微改一下就好
Array.prototype.myforeach = async function (fn, context = null) {
let index = 0;
let arr = this;
if (typeof fn !== 'function') {
throw new TypeError(fn + ' is not a function');
}
while (index < arr.length) {
if (index in arr) {
try {
await fn.call(context, arr[index], index, arr);
} catch (e) {
console.log(e);
}
}
index ++;
}
};
为什么 await 在 forEach 中不生效?如何解决?
最新推荐文章于 2024-07-03 12:08:35 发布