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!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM