javascript 循环中调用异步的同步需求

// 关于Promise:可以直接使用promise
Promise.resolve(123).then(v => {
    console.log(v)
})

// 循环中调用异步
let arr = []
new Promise((res, rej) => {
    for (let index = 0; index < 5; index++) {
        new Promise((resolve, reject) => {
            resolve(index)
        })
        .then((i) => {
            arr.push(index)
        })
    }
    res()
}).then(() => {
    console.log(arr)
})


// -----

// async/await 版本 循环(forEach)中调用异步
async function processArray(array) {
    if(toString.call(array) != '[object Array]'){
        console.log(array)
        return
    }
    array.forEach(async (item) => {
        await processArray(item);
    })
    console.log('Done!');
}
processArray(['a', 'b', 'c'])

// 结果:像同步一样的预期结果
// a
// b
// c
// Done!

猜你喜欢

转载自www.cnblogs.com/CoderMonkie/p/js-async-in-loop.html