猿问

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

如果另一个函数返回为真,我有一个应该运行的函数:


// in utils.js

methods:{

  funcOne(){

    // do some thing

    return true

  }

}



//in component.vue

methods:{

  funcTwo(){

    let x = this.funcOne()

    if(x){

    // do something

    }else{

    // do something

    }

  }

}


我怎样才能做到这一点?因为 js 是运行时的,所以它不会等待结果,funcOne()我知道我应该使用Promiseor async/await。但不知道怎么办!!


湖上湖
浏览 104回答 2
2回答

一只名叫tom的猫

因为 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    }  }}

繁星点点滴滴

methods:{  async funcOne(){    // do some thing    await someAsyncFunctionOrLogic();    return true  }}//in component.vuemethods:{  async funcTwo(){    let x = await this.funcOne()    if(x){    // do something    }else{    // do something    }  }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答