为了账号安全,请及时绑定邮箱和手机立即绑定

如何在异步等待中使用一个函数导致另一个函数

如何在异步等待中使用一个函数导致另一个函数

湖上湖 2022-12-29 10:35:29
如果另一个函数返回为真,我有一个应该运行的函数:// 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 是运行时的,所以它不会等待结果,funcOne()我知道我应该使用Promiseor async/await。但不知道怎么办!!
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

因为 js 是运行时的,所以它不会等待结果funcOne()

由于funcOne() 您的示例代码中的不是异步函数,因此这是不正确的:调用等待函数完成并返回其值。

我怎样才能做到这一点?[...] 我知道我应该使用 Promise 或async/await. 但不知道怎么办!!

那么你最好阅读Promises 的文档和函数async/await语法,因为你需要对它们有正确的理解才能有效地使用它。

更新

现在到你的实际代码:你的实现sweetAlert()实际上并没有返回任何东西,因为returns 的范围是另一个函数:

# 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()处理程序的函数。该链将返回另一个 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另请注意,您不在函数中使用await(sweetAlert()但仅在其中的其他函数中使用)并返回 aPromise而不是原始值,您可以省略async它的关键字。


或者,您可以完全使用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

    }

  }

}


查看完整回答
反对 回复 2022-12-29
?
繁星点点滴滴

TA贡献1803条经验 获得超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

    }

  }

}


查看完整回答
反对 回复 2022-12-29
  • 2 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号