Javascript的promise,async和await的區(qū)別詳解
終于把promise, async, await的區(qū)別和聯(lián)系弄清楚了,看下面代碼
寫法1,2是promise的寫法
寫法6是async和await的寫法
主要看第2種寫法和第6中寫法即可, 第2種寫法是promise的典型寫法,第6中寫法是async, await的典型寫法
// 以下三個請求依次執(zhí)行
req1 = () => { return fetch("http://example.com/api/v1/get")}
req2 = () => { return fetch("http://example.com/api/v1/post")}
req3 = () => { return fetch("http://example.com/api/v1/delete")}
//寫法1
req1().then(res=>{
console.log("1: ",res)
req2().then(res =>{
console.log("2: ",res)
req3().then(res =>{
console.log("3: ",res)
})
})
})
// 寫法2
req1().then(res =>{
console.log("1: ", res)
return req2()
})
.then(res =>{
console.log("2: ", res)
return req3()
})
.then(res =>{
console.log("3: ", res)
})
// 寫法3
function f1(){
req1()
req2()
req3()
}
// 寫法4
async function f2(){
await req1
await req2
await req3
}
// 寫法5
async function f3(){
req1().then(res => {
console.log("1:", res)
})
await f3_1()
}
async function f3_1(){
req1().then(res => {
console.log("2:", res)
})
await f3_2()
}
async function f3_2(){
req2().then(res=>{
console.log("3: ",res)
})
}
// 寫法6
ff()
async function ff(){
await req1_good()
}
async function req1_good(){
fetch("http://example.com/api/v1/get").then(res =>{
console.log("1: ",res)
})
await req2_good()
}
async function req2_good() {
fetch("http://example.com/api/v1/post").then(res =>{
console.log("2: ",res)
})
await req3_good()
}
async function req3_good() {
fetch("http://example.com/api/v1/delete").then(res => {
console.log("3: ",res)
})
}
- 最外層的async函數(shù)調(diào)用之后立即返回了,但是async還是里面還是在逐層執(zhí)行
- await的作用是等待其修飾的函數(shù)內(nèi)部的所有await函數(shù)都執(zhí)行完畢,
- 從最外層啟動一個async函數(shù)相當(dāng)于go一個協(xié)程,await func 也相當(dāng)于go 一個協(xié)程,不同在于await = go + waitgroup
- await比promise高明的地方在于,promise在then里面調(diào)用另一個promise時,不得不return另一個promise再then, 或者在then中回調(diào),但是await完全不需要
- async是為了異步,await是為了異步+阻塞,缺一不可
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
javascript 模擬坦克大戰(zhàn)游戲(html5版)附源碼下載
這篇文章主要介紹了javascript 模擬坦克大戰(zhàn)游戲關(guān)鍵點和遇到的問題及實現(xiàn)代碼,需要的朋友可以參考下2014-04-04
Websocket通信協(xié)議在數(shù)字孿生中的應(yīng)用
這篇文章主要為大家介紹了Websocket通信協(xié)議在數(shù)字孿生中的應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
js change,propertychange,input事件小議
github上關(guān)于mootools一個issue的討論很有意思,所以就想測試記錄下。感興趣的可以點擊原頁面看看2011-12-12
小程序卡片切換效果組件wxCardSwiper的實現(xiàn)
這篇文章主要介紹了小程序卡片切換效果組件wxCardSwiper的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
CKEditor 4.4.1 添加代碼高亮顯示插件功能教程【使用官方推薦Code Snippet插件】
這篇文章主要介紹了CKEditor 4.4.1 添加代碼高亮顯示插件功能,涉及ckeditor使用官方推薦Code Snippet插件的相關(guān)操作布局與使用注意事項,需要的朋友可以參考下2019-06-06

