欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript的promise,async和await的區(qū)別詳解

 更新時(shí)間:2022年03月23日 16:33:37   作者:河流兒  
這篇文章主要為大家詳細(xì)介紹了Javascript的promise,async和await的區(qū)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

終于把promise, async, await的區(qū)別和聯(lián)系弄清楚了,看下面代碼

寫法1,2是promise的寫法

寫法6是async和await的寫法

主要看第2種寫法和第6中寫法即可, 第2種寫法是promise的典型寫法,第6中寫法是async, await的典型寫法

// 以下三個(gè)請(qǐng)求依次執(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í)行完畢,
  • 從最外層啟動(dòng)一個(gè)async函數(shù)相當(dāng)于go一個(gè)協(xié)程,await func 也相當(dāng)于go 一個(gè)協(xié)程,不同在于await = go + waitgroup
  • await比promise高明的地方在于,promise在then里面調(diào)用另一個(gè)promise時(shí),不得不return另一個(gè)promise再then, 或者在then中回調(diào),但是await完全不需要
  • async是為了異步,await是為了異步+阻塞,缺一不可

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!   

相關(guān)文章

最新評(píng)論