一.Promisejavascript
1.返回一個promise對象,函數前面的async
一詞意味着一個簡單的事情:這個函數老是返回一個promise,若是代碼中有return <非promise>
語句,JavaScript會自動把返回的這個value值包裝成promise的resolved值。java
2.<1>關鍵詞await
可讓JavaScript進行等待(相似於then),直到一個promise執行並返回它的結果,JavaScript纔會繼續往下執行。git
<2>await只能在async中使用github
<3>await後面要是promise對象json
eg1:如下是一個promise在1s以後resolve的例子:api
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 1000)
})
let result = await promise // 直到promise返回一個resolve值(*)
alert(result) // 'done!'
}
f()promise
eg2:app
async function showAvatar() {
// read our JSON
let response = await fetch('/article/promise-chaining/user.json')
let user = await response.json()
// read github user
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`)
let githubUser = await githubResponse.json()
// 展現頭像
let img = document.createElement('img')
img.src = githubUser.avatar_url
img.className = 'promise-avatar-example'
documenmt.body.append(img)
// 等待3s
await new Promise((resolve, reject) => {
setTimeout(resolve, 3000)
})
img.remove()
return githubUser
}
showAvatar()異步
3.錯誤處理async
await 命令後面的 Promise 對象,運行結果多是 rejected,因此最好把 await 命令放在 try...catch 代碼塊中。
async function myFunction() { try { await somethingThatReturnsAPromise(); } catch (err) { console.log(err); } } // 另外一種寫法 async function myFunction() { await somethingThatReturnsAPromise().catch(function (err){ console.log(err); }); }
4.async await同步執行多個異步代碼
async function f() { let promise1 = new Promise((resolve, reject) => { setTimeout(() => resolve('1000'), 1000) }) let promise2 = new Promise((resolve, reject) => { setTimeout(() => resolve('2000'), 2000) }) let promise3 = new Promise((resolve, reject) => { setTimeout(() => resolve('3000'), 3000) }) let promise4 = new Promise((resolve, reject) => { setTimeout(() => resolve('4000'), 4000) }) let result1 = await promise4 console.log(result1) let result2 = await promise3 console.log(result2) let result3 = await promise2 console.log(result3) let result4 = await promise1 console.log(result4) } f()