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