async await的串行与并行
创建两个promise
const fn1 = () => {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(new Date())
},2000)
})
}
const fn2 = () => {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(new Date())
},4000)
})
}
async await的串行对应promise的链式调用
输出时间间隔2秒和4秒,说明promise串行执行
//async await的串行
(async ()=>{
console.log(new Date())
const time1 = await fn1()
console.log(time1)
const time2 = await fn2()
console.log(time2)
})()
//async await的串行等同与promise的链式调用相同
console.log(new Date())
fn1().then(resolve=>{
console.log(resolve)
return fn2()
}).then(resolve=>{
console.log(resolve)
})
async await的并行对应promise.all
输出时间间隔2秒和2秒,说明promise并行执行
//async await的并行
(async ()=>{
console.log(new Date())
//在promise对象被创建的时候,立即调用(resolve,reject)=>{}函数
const promise1 = fn1()
const promise2 = fn2()
console.log(await promise1)
console.log(await promise2)
})()
//async await的并行相当于promise.all
console.log(new Date())
Promise.all([fn1(),fn2()]).then(resolve=>{
console.log(resolve)
})