标签:turn wait process string ons foreach proc roc asc
// 关于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!
标签:turn wait process string ons foreach proc roc asc
原文地址:https://www.cnblogs.com/CoderMonkie/p/js-async-in-loop.html