一、async/await在forEach中为什么不起作用
当你在forEach 循环内调用异步函数,下一个循环并不会等到上个循环结果后再被调用。 想象一下,你有一个 getUsers 方法返回用户列表 User , user只有用户列表,但不包含具体的detail信息,所以你使用forEach 试图去获取用户详情。如果就有了如下的代码:
const users = await getUsers();
users.forEach(user => {
const details = user.getDetails();
console.log(details);
})
打印结果却是 3 个pending状态的 promise 于是你很自然的想到了getDetails是个异步函数,需要给他加上await关键字。
const users = await getUsers();
users.forEach(user => {
const details = await user.getDetails();
console.log(details);
})
这时候运行发现了一个报错:
SyntaxError: await is only valid in async function
你意识到如果forEach传递的函数如果有异步的,需要用async标记异步函数 再次修改它
const users = await getUsers();
users.forEach(async (user) => {
const details = await user.getDetails();
console.log(details);
})
问题解决了,但是你会发现,你盯着半天发现结果并没有按照users的顺序输出的结果。
二、解决方案
你需要使用for循环来代替forEach来循环重写这部分代码
const users = await getUsers();
for (let i = 0; i < users.length; i++) {
const details = await user.getDetails();
console.log(details);
}
也可以使用 for .... of
const users = await getUsers();
for (const user of users) {
const details = await user.getDetails();
console.log(details);
}
如果你实在不喜欢简单的代码,那么可以用个小技巧 使用 Array 的 map 方法
const users = await getUsers();
const userDetailsPromises = users.map(user => user.getDetails());
const userDetails = await Promise.all(userDetailsPromises);
console.log(userDetails);
分析:
分析上边的这个代码
1、第一行代码获取users的数组
2、map循环调用getDetails返回新的userDetailsPromises 数组,数组元素都为Promise类型
3、使用await Promise.all等待所有Promise处理完毕
4、最后打印出结果数组
代码简化:
const userDetails = await Promise.all(users.map(user => user.getDetails()));
三、forEach的源码
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
可以看到forEach内部就是一个while循环,然后内部去执行这个回调函数,并没有对异步进行什么处理。
五、留一个问题
比较下下边两个代码输出有何不同?
const sleep = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const arr = [
() => console.log("start"),
() => sleep(1000),
() => console.log(1),
() => sleep(1000),
() => console.log(2),
() => sleep(1000),
() => console.log(3),
() => sleep(1000),
() => console.log("end")
]
arr.forEach(async fn => {
await fn()
})
const sleep = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const arr = [
() => console.log("start"),
() => sleep(1000),
() => console.log(1),
() => sleep(1000),
() => console.log(2),
() => sleep(1000),
() => console.log(3),
() => sleep(1000),
() => console.log("end")
]
async function run(arr) {
for (let i = 0; i < arr.length; i++) {
await arr[i]()
}
}
run(arr)