错误写法
function api(i) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const n = Math.random();
if (n > 0.5) {
resolve(n);
} else {
resolve(-n)
}
}, 1000 * 1);
});
}
const list = [1, 2, 3, 4, 5];
async function fn() {
// 数组forEach遍历方法 await无效
list.forEach(async (el, index) => {
const n = await api(index);
console.log(n, index);
});
};
fn();
正确写法
function api(i) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const n = Math.random();
if (n > 0.5) {
resolve(n);
} else {
resolve(-n)
}
}, 1000 * 1);
});
}
const list = [1, 2, 3, 4, 5];
async function fn() {
for (let i = 0; i < list.length; i++) {
const n = await api(i);
console.log('for--------', n, i);
}
};
fn();
await要写在async函数里面,await只是语法糖,使异步变成同步,便于书写和阅读。await 等待异步的promise函数执行完成resolve或者reject,抛异常使用try catch。forEach使用await无效,改用for循环