# async awit 異步 https://www.youtube.com/watch?v=_9vgd9XKlDQ https://www.bilibili.com/video/BV15J411G7FG?p=4&spm_id_from=pageDriver 超強 ## iife 立刻執行  ## try catch 找錯誤 但如果returen promise的話 要用catch接 ## promise all  要配合await 不然容易出錯 結果也用all的原因 要全部對 Promise.all() 方法回傳一個 Promise 物件,當引數 iterable 中所有的 promises 都被實現(resolved),或引數 iterable 不含任何 promise 時,被實現。或以第一個被拒絕的 promise 的原因被拒絕。 ## all vs race Promise.all 透過陣列的形式傳入多個 promise 函式,在全部執行完成後回傳陣列結果,陣列的結果順序與一開始傳入的一致。 ``` Promise.all([promise(1), promise(2), promise(3, 3000)]) .then(res => { console.log(res); }); ``` 這個方法很適合用在多支 API 要一起執行,並確保全部完成後才進行其他工作時。 Promise.race 透過陣列的形式傳入多個 promise 函式,在全部執行完成後回傳單一結果,結果為第一個運行完成的,以下範例來說就會回傳 promise(1) 的結果。 ``` Promise.race([promise(1), promise(2), promise(3, 3000)]).then(res => { console.log(res); }); ``` 這個方法可以用在站點不穩定,同時發送多支同行為 API 確保可行性使用,但實作中使用率並不高。 ###### tags: `javaScript`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up