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

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

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

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

湖上湖 2022-12-29 10:35:29
如果另一個函數(shù)返回為真,我有一個應(yīng)該運行的函數(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    }  }}我怎樣才能做到這一點?因為 js 是運行時的,所以它不會等待結(jié)果,funcOne()我知道我應(yīng)該使用Promiseor async/await。但不知道怎么辦?。?
查看完整描述

2 回答

?
一只名叫tom的貓

TA貢獻1906條經(jīng)驗 獲得超3個贊

因為 js 是運行時的,所以它不會等待結(jié)果funcOne()

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

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

那么你最好閱讀Promises 的文檔和函數(shù)async/await語法,因為你需要對它們有正確的理解才能有效地使用它。

更新

現(xiàn)在到你的實際代碼:你的實現(xiàn)sweetAlert()實際上并沒有返回任何東西,因為returns 的范圍是另一個函數(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實際上作用于傳遞給then()處理程序的函數(shù)。該鏈將返回另一個 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

    })

  }

}

請注意,如果它進入第一個塊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
?
繁星點點滴滴

TA貢獻1803條經(jīng)驗 獲得超3個贊

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)注
  • 83 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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