Promise & async/await 场景需求题
machao07 opened this issue · comments
例:
function getTime(seconds){
return new Promise(resolve=>{
setTimeout(() => {
console.log('setTimeout===',seconds)
resolve(seconds)
}, seconds);
})
}
function test(){
let arr = [getTime(2000), getTime(300), getTime(1000)]
for (let x of arr){
console.log('arr===',x);
}
}
test()
打印结果分析:
- for...of 遍历 arr 依次打印 Promise
- Promise 中 setTimeout 时间延时打印
- setTimeout 宏观任务 后执行
有多个不定数异步任务,需要依次返回
function getTime(seconds){
return new Promise(resolve=>{
setTimeout(() => {
console.log('setTimeout===',seconds)
resolve(seconds)
}, seconds);
})
}
async function test(){
let arr = [getTime(2000), getTime(300), getTime(1000)]
for await (let x of arr){
console.log('arr===',x);
}
}
test()
打印结果分析:
setTtimeout
先执行await
需要等待 getTime 执行后for await...of
按照数组依次打印 2000、300、1000
延迟执行
function delayRun(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
// promise
delayRun(5000).then(() => console.log('promise 延迟5秒'))
// async/await
async function delayRunAsc() {
let result = await delayRun(3000)
console.log('async 延迟3秒')
return result
}
delayRunAsc()
打印结果:
Promise、async/await、setTimeout执行顺序
async function async1() {
console.log('async1 start');
await async2();
console.log('asnyc1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(() => {
console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
console.log('promise1');
reslove();
}).then(function () {
console.log('promise2');
})
console.log('script end');
打印结果分析:
async
函数中没有 await,执行等同于普通函数await
是一个让出线程的标志, 阻塞async内后续的代码,先去执行async外的代码(promise1
优先于async1 end
)
async/await 与 forEach、for...of
function getTime(seconds){
return new Promise(resolve=>{
console.log('new Promise===',seconds)
setTimeout(() => {
console.log('setTimeout===',seconds)
resolve(seconds)
}, seconds);
})
}
// forEach
function test(){
let arr = [2000, 300, 1000]
arr.forEach(async item => {
const x = await getTime(item)
console.log('arr===',x);
})
}
// for...of
async function test(){
let arr = [2000, 300, 1000]
for (let item of arr){
const x = await getTime(item)
console.log('arr===',x);
}
}
test()
forEach 输出
- 先同时输出 new Promise
- 依次时间延时打印
for...of 输出