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