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!
作者:码路工人
公众号:码路工人有力量(Code-Power)
欢迎关注个人微信公众号 Coder-Power
一起学习提高吧~
![](https://gitee.com/Coding-Worker/picture/raw/master/2021-1-5/1609860559027-qrcode_for_gh_e1903e0c25a7_258.jpg)
posted on 2020-02-11 18:06 CoderMonkey 阅读(1480) 评论(0) 编辑 收藏 举报