第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

如何在異步等待中使用一個(gè)函數(shù)導(dǎo)致另一個(gè)函數(shù)

如何在異步等待中使用一個(gè)函數(shù)導(dǎo)致另一個(gè)函數(shù)

湖上湖 2022-12-29 10:35:29
如果另一個(gè)函數(shù)返回為真,我有一個(gè)應(yīng)該運(yùn)行的函數(shù):// in utils.jsmethods:{  funcOne(){    // do some thing    return true  }}//in component.vuemethods:{  funcTwo(){    let x = this.funcOne()    if(x){    // do something    }else{    // do something    }  }}我怎樣才能做到這一點(diǎn)?因?yàn)?js 是運(yùn)行時(shí)的,所以它不會等待結(jié)果,funcOne()我知道我應(yīng)該使用Promiseor async/await。但不知道怎么辦??!
查看完整描述

2 回答

?
一只名叫tom的貓

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊

因?yàn)?js 是運(yùn)行時(shí)的,所以它不會等待結(jié)果funcOne()

由于funcOne() 您的示例代碼中的不是異步函數(shù),因此這是不正確的:調(diào)用等待函數(shù)完成并返回其值。

我怎樣才能做到這一點(diǎn)?[...] 我知道我應(yīng)該使用 Promise 或async/await. 但不知道怎么辦!!

那么你最好閱讀Promises 的文檔和函數(shù)async/await語法,因?yàn)槟阈枰獙λ鼈冇姓_的理解才能有效地使用它。

更新

現(xiàn)在到你的實(shí)際代碼:你的實(shí)現(xiàn)sweetAlert()實(shí)際上并沒有返回任何東西,因?yàn)?code>returns 的范圍是另一個(gè)函數(shù):

# abbreviated code:

async function sweetAlert(options) {

  if (...) {

    this.$swal({...}).then(async (result) => {

      if (...) {

        let res = await options.callback(options.cValue)

        return res

      }


      return true

    })

  }

}

所以return res和return true實(shí)際上作用于傳遞給then()處理程序的函數(shù)。該鏈將返回另一個(gè) promise,該 promise 將以 thatreturn的值解析。要將此作為sweetAlert()您需要的返回值return:


# abbreviated code:

function sweetAlert(options) {

  if (...) {

    // return the result of the chain here for sweetAlert()

    return this.$swal({...}).then(async (result) => {

      if (...) {

        let res = await options.callback(options.cValue)

        return res

      }


      return true

    })

  }

}

請注意,如果它進(jìn)入第一個(gè)塊sweetAlert(),它只會返回一些東西。if另請注意,您不在函數(shù)中使用await(sweetAlert()但僅在其中的其他函數(shù)中使用)并返回 aPromise而不是原始值,您可以省略async它的關(guān)鍵字。


或者,您可以完全使用async/await:


async function sweetAlert(options) {

  if (options.method === 'confirm' || options.method === 'callback') {

    // await the return value here

    let result = await this.$swal({...})


    if (result.value) {

      if (options.method === 'callback') {

        let res = await options.callback(options.cValue)

        return res

      }


      // now this will return from sweetAlert()

      return true

    }

  }

}


查看完整回答
反對 回復(fù) 2022-12-29
?
繁星點(diǎn)點(diǎn)滴滴

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊

methods:{

  async funcOne(){

    // do some thing

    await someAsyncFunctionOrLogic();

    return true

  }

}



//in component.vue

methods:{

  async funcTwo(){

    let x = await this.funcOne()

    if(x){

    // do something

    }else{

    // do something

    }

  }

}


查看完整回答
反對 回復(fù) 2022-12-29
  • 2 回答
  • 0 關(guān)注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號