Async 和 Awaiit 是 Promise 的擴展,我們知道 JavaScript 是單執行緒的,使用 Promise 之后可以使異步操作的書寫更簡潔,而 Async 使 Promise 像同步操作
一、Async
Async 自動將常規函式轉換成 Promise,回傳值一個 Promise 物件,使用 async 的效果:
async function f() { return 123 }
console.log(f()) // Promise 物件
async function f() { return 123 }
f().then(console.log) // 123
可以看出,f() 的回傳值有 then 方法(在 JavaScript 中只有原生 Promise 物件擁有 then 方法)
console.log(f() instanceof Promise) // true
通過驗證,我們知道想獲得一個 Promise 物件,可以不用再使用 new Promise 了,可以用 async 來實作
另外,async 函式顯示回傳的結果如果不是 Promise,會自動包裝成 Promise 物件,也就是說上面的代碼等同于:
async function f() { return Promise.resolve(123) }
二、Await
Await 放置在 Promise 呼叫之前,強制后面的代碼等待,直到 Promise 物件 resolve,得到 resolve 的值作為 await 運算式的運算結果
未使用 await 的效果:
async function f() { let promise = new Promise((resolve) => { setTimeout(() => resolve(123), 1000) }) console.log(promise.then(val => console.log(val))) console.log(456) } f()
輸出:
![]()
使用 await 的效果:
async function f() { let promise = new Promise((resolve) => { setTimeout(() => resolve(123), 1000) }) console.log(await promise) console.log(456) } f()
輸出:
![]()
await 的字面意思為“等待”,它等什么呢?等的是 Promise 的回傳結果,上面這段代碼由 async 開啟一個 Promise 物件,函式內部嵌套了一個 Promise 操作,這個操作需要等待 1 秒才回傳“123”的結果,也就是說 await 在拿到這個結果之前不會執行后面的代碼,會一直等到拿到這個結果才往后繼續執行
注意:
- await 后面如果不是 Promise 物件會自動包裝成 Promise 物件
- await 只能在 async 函式內部使用,否則會報錯
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/115138.html
標籤:JavaScript
上一篇:HTML入門基礎
下一篇:1.react初識
