1、首先需要理解async 和 await的基本含義
async 是一個(gè)修飾符,async 定義的函數(shù)會(huì)默認(rèn)的返回一個(gè)Promise對象resolve的值,因此對async函數(shù)可以直接進(jìn)行then操作,返回的值即為then方法的傳入函數(shù)
// 0. async基礎(chǔ)用法測試 async function fun0() { console.log(1) return 1 } fun0().then( x => { console.log(x) }) // 輸出結(jié)果 1, 1, async function funa() { console.log('a') return 'a' } funa().then( x => { console.log(x) }) // 輸出結(jié)果a, a, async function funo() { console.log({}) return {} } funo().then( x => { console.log(x) }) // 輸出結(jié)果 {} {} async function funp() { console.log('Promise') return new Promise(function(resolve, reject){ resolve('Promise') }) } funp().then( x => { console.log(x) }) // 輸出promise promise
await 也是一個(gè)修飾符,
await 關(guān)鍵字 只能放在 async 函數(shù)內(nèi)部, await關(guān)鍵字的作用 就是獲取 Promise中返回的內(nèi)容, 獲取的是Promise函數(shù)中resolve或者reject的值
// 如果await 后面并不是一個(gè)Promise的返回值,則會(huì)按照同步程序返回值處理
// await 關(guān)鍵字 只能放在 async 函數(shù)內(nèi)部, await關(guān)鍵字的作用 就是獲取 Promise中返回的內(nèi)容, 獲取的是Promise函數(shù) 中resolve或者reject的值 // 如果await 后面并不是一個(gè)Promise的返回值,則會(huì)按照同步程序返回值處理,為undefined const bbb = function(){ return 'string'} async function funAsy() { const a = await 1 const b = await new Promise((resolve, reject)=>{ setTimeout(function(){ resolve('time') }, 3000) }) const c = await bbb() console.log(a, b, c) } funAsy() // 運(yùn)行結(jié)果是 3秒鐘之后 ,輸出 1, time , string,
// 2.如果不使用promise的方法的話 function log2(time) { setTimeout(function(){ console.log(time) return 1 }, time) } async function fun1() { const a = await log2(5000) const b = await log2(10000) const c = log2(2000) console.log(a) console.log(1) } fun1() // 以上運(yùn)行結(jié)果為: 立刻輸出undefined 立刻輸出1 2秒后輸出2000 5秒后輸出5000 10秒后輸出10000
2、那么由此看來async / await的綜合用法如下
// 1.定義一個(gè)或多個(gè)普通函數(shù),函數(shù)必須返回Promise對象,如果返回其他類型的數(shù)據(jù),將按照普通同步程序處理 function log(time) { return new Promise((resolve, reject)=> { setTimeout(function(){ console.log(time) resolve() }, time) }) } async function fun() { await log(5000) await log(10000) log(1000) console.log(1) } fun()
// 3. async / await的重要應(yīng)用 const asy = function(x, time) { return new Promise((resolve, reject) =>{ setTimeout(()=>{ resolve(x) }, time) }) } const add = async function() { const a = await asy(3, 5000) console.log(a) const b = await asy(4, 10000) console.log(b) const c = await asy(5, 15000) console.log(a,b,c) const d = a + b +c console.log(d) } add(); // 5秒后輸出3 又10秒后輸出4 又15秒后輸出5 然后立刻輸出3,4,5,然后輸出12