JS異步操作新體驗之 async函數(shù)

文章來自https://www.cnblogs.com/rogerwu/p/10784236.html

async 函數(shù)返回一個 Promise 實例對象,可以使用 then 方法添加回調(diào)函數(shù)。

當(dāng)函數(shù)執(zhí)行時,一旦遇到 await 就會先返回,等到異步操作完成,再接著執(zhí)行函數(shù)體內(nèi)后面的語句

function sleep(ms) { return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

async function print(ms) {
  console.log('start... ...')
  await sleep(ms)
  console.log('end... ...')
}

print(1000)
image

(1)、async 函數(shù)內(nèi)部 return語句返回的值,會成為then方法回調(diào)函數(shù)的參數(shù)

async function foo() { return 'hello world' }

foo().then(res => console.log(res))   // hello world

(2)、async 函數(shù)內(nèi)部拋出錯誤,會導(dǎo)致返回的 Promise對象變成reject狀態(tài),拋出的錯誤會被catch方法回調(diào)函數(shù)接收到

async function bar() { return new Error('Error... ...')
}

bar().then(res => console.log(res))
     .catch(err => console.log(err))   // Error: Error... ...

(3)、只有 async 函數(shù)內(nèi)部的異步操作執(zhí)行完,才會執(zhí)行 then方法指定的回調(diào)函數(shù)

async function baz() {
  await new Promise(resolve => {
    console.log('執(zhí)行第一個異步操作')
    setTimeout(resolve, 2000)
  })

  await new Promise(resolve => {
    console.log('執(zhí)行第二個異步操作')
    setTimeout(resolve, 3000)
  }) return '異步執(zhí)行完畢再執(zhí)行then方法' }

baz().then(res => {console.log(res)})
image

實際應(yīng)用

getDetail(id){
    return new Promise(resolve => {
        let _this = this;
        let param = {
            goodsId:id,
        }
        api.getVideoDetails(param,function(success,data,err){
            if(success) {
                if(data.status == 200) {
                    _this.detail = data.body
                }
            }
            resolve()
        })
    })
},
toCourseDetail: async function(id){
    let _this = this;
    await _this.getDetail(id)
    console.log('jfksjklfj'+_this.detail.course)
    // 接口返回值后,再使用this.detail
},
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容