一、async 函數返回一個Promise對象promise
onLoad: function (options) { async function list(){ return 'aaa' } console.log(list()) },
輸出異步
Promise {<resolved>: "aaa"}
二、await 就是異步等待,後面應該跟一個Promise對象,若是不是Promise對象,那麼會被轉成一個當即 resolve 的Promiseasync
三、await 等待的是一個Promise對象,會將Promise對象的resolve狀態的值返回,而不是返回Promise對象函數
onLoad: async function (options) { const aa = await this.promise1() //沒有await console.log(aa) }, promise1(){ return new Promise((resolve, reject) => { resolve('aaaa') }) },
輸出 Promise對象this
Promise {<resolved>: "aaaa"}
onLoad: async function (options) { const aa = await this.promise1() //有await console.log(aa) }, promise1(){ return new Promise((resolve, reject) => { resolve('aaaa') }) },
輸出 Promise對象resolve的值spa
aaaa
四、程序中只要有Promise對象返回reject狀態,就會拋出異常,有await(等待一個異常)會阻止下邊代碼的執行,沒有await下邊代碼會正常執行(最後再拋出異常)code
異常最後拋出;異常中會附帶reject的值;會拋出多個異常,若是存在多個reject狀態的Promise對象
對象
onLoad: async function (options) { const aa = await this.promise1() //沒有await console.log(aa) }, promise1() { return new Promise((resolve, reject) => { reject('aaaa') }) },
最後拋出異常,沒有await,下邊程序正常執行blog
Promise {<rejected>: "aaaa"} Uncaught (in promise) aaaa
五、await 等待的Promise對象返回了reject狀態,程序就會拋出異常,await後邊的程序不會執行it
onLoad: async function (options) {
const aa = await this.promise1() console.log(aa) }, promise1() { return new Promise((resolve, reject) => { reject('aaaa') }) },
程序拋出異常,有await,await下邊的程序不會執行
Uncaught (in promise) aaaa
六、await並非等待他裏邊的代碼執行完成以後,才執行下邊的代碼, await的意思遲早會執行,只是遇到等待的promise對象返回reject狀態時,await後邊的代碼纔不會執行
function testSometing() { console.log("執行testSometing"); return "testSometing"; } async function testAsync() { console.log("執行testAsync"); return Promise.resolve("hello async"); } async function test() { console.log("test start..."); const v1 = await testSometing();//關鍵點1 console.log(v1); const v2 = await testAsync(); console.log(v2); console.log(v1, v2); } test(); var promise = new Promise((resolve)=> { console.log("promise start.."); resolve("promise");});//關鍵點2 promise.then((val)=> console.log(val)); console.log("test end...")
輸出結果
test start... 執行testSometing promise start.. test end... testSometing 執行testAsync promise hello async testSometing hello async