1. 程式人生 > >async await promise

async await promise

log 也有 ons new 一行代碼 ole nbsp blog 沒有

async 異步函數,以後可能會用得很廣。

1、箭頭函數: 沒有{}時不寫return 也有返回值

2、Promise : 異步神器,很多異步api都是基於Promise

3、new Promise().then().then().catch() :第一個then觸發條件:是 Promise() 實例化時resolve()觸發, 第二個及以後的then() 觸發條件是前一個then() 代碼被執行一遍,不包括異步代碼,如果有return,後面的代碼不再執行,並且將return值作為下一個then的參數

4、async: 異步函數,可以使用await 等待promise resolve的結果,是基於Promise的

5、await : 後面必須跟Promise對象,若非Promise,則不會攔截後面代碼執行。當promise對象resolve過後並且執行完then裏面的代碼,就執行下一步代碼,不resolve不會觸發下一行代碼執行。

需註意:如果then()中需要異步操作,不會等then中的異步執行完過後再執行下一個then()的函數。原因就是,異步函數中,沒有地方給你return給then()回調函數。解決方案是async函數。

也就是說Promise對於異步的幫助 其實很有限,.then()就只有第一個有用而已。

 1   const aa = _ => new Promise((res, rej) => { // 設置aa函數返回promise對象
2 setTimeout(function() { 3 console.log(‘1‘) 4 res(‘2‘) 5 }, 1000); 6 }) 7 let bb = async function() { 8 await aa().then((res) => { // await會等待aa()執行完,並且then代碼也執行完,當然,then代碼裏面的異步操作不會執行。 9 console.log(res) 10 setTimeout(function
(){ // 我在這兒then中寫了一個異步函數,這樣寫毫無意義, 11 console.log(‘4‘) // return的值到了setTimeout()的函數中,then中的代碼執行完直接進入下一個then 12 return ‘sdf‘ 13 }, 2000) 14 }).then(res => { 15 console.log(res) // undifined 16 }) 17 console.log(‘3‘) 18 } 19 console.log(bb()) // Promise {<pending>}
// console 結果 :
Promise { <pending> }
1
2
undifined
3
4


async await promise