async,await陨亡,promise.all()應(yīng)用簡單的描述唉匾,同步處理異步农尖,await字面意思等待。
首先三個(gè)promise,實(shí)際應(yīng)用可以看為axios請求嘛
let runA = function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("2秒后 runA方法執(zhí)行完畢")
resolve(new Date())
}, 2000)
})
}
let runB = function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("4秒后 runB方法執(zhí)行完畢")
resolve(new Date())
}, 4000)
})
}
let runC = (function () {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("6秒后 runC方法執(zhí)行完畢")
resolve(new Date())
}, 6000)
})
})
async,await
async function awaitText() {
console.log(new Date())
await runA().then(res=>console.log(res))
await runB().then(res=>console.log(res))
await runC().then(res=>console.log(res))
}
awaitText()
返回值
async
promise.all
Promise.all([runA(),runB(),runC()])
.then(res=>{
console.log(res)
})
Promise.all
promise.all()異步函數(shù)并行執(zhí)行篷角,時(shí)間短 總耗時(shí)取決于用時(shí)最長的異步,從最后一個(gè)和第一個(gè)相差4秒可以看出
async,await按照順序執(zhí)行乳附,時(shí)間長 總耗時(shí) 2+4+6
注重代碼順序内地,采用async,await