forEach
// 模拟异步请求
function gets(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x)
}, 1000 * x)
})
};
function fn() {
let arr = [3, 2, 1]
arr.forEach(async item => {
const res = await gets(item)
console.log(res)
})
};
// 1s后 => 输出1 ,2s后 => 输出1,3s后 => 输出1
// 输出顺寻并未按照 [3, 2, 1] 3,2,1顺序
fn();
for of 按照顺序间隔输出
// 模拟异步请求
function gets(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x)
}, 1000 * x)
})
};
async function fnAwait() {
let arr = [2, 3, 1]
for (const item of arr) {
const res = await gets(item)
console.l

本文探讨了JavaScript中`for await of`的使用,强调了它如何确保序列执行并提供一个DEMO示例来说明其工作原理。
最低0.47元/天 解锁文章

160

被折叠的 条评论
为什么被折叠?



