[Vuejs]-How to use a function result in another function with async await

1πŸ‘

βœ…

as js is runtime it won’t wait for result of funcOne()

Since the funcOne() in your example code is not an async function this is not correct: the call will wait for the function to complete and return its value.

how can i do this? […] and i know i should be using Promise or async/await. but dont know how!!

Then it is probably best for you to read on the documentation for Promises and the async/await Syntax for functions since you need a proper understanding of them to use it effectively.

Update

Now to your actual code: your implementation of sweetAlert() does not actually return anything because the returns are scoped to another function:

# abbreviated code:
async function sweetAlert(options) {
  if (...) {
    this.$swal({...}).then(async (result) => {
      if (...) {
        let res = await options.callback(options.cValue)
        return res
      }

      return true
    })
  }
}

So the return res and return true are actually scoped to the function which is passed to the then() handler. This chain will return another promise which will resolve with the value of that returns. To catch this as the return value of sweetAlert() you need to return it:

# 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
    })
  }
}

Note that sweetAlert() will only return something if it enters the first if block. Also note that you don’t use await in the sweetAlert() functions (but only in other functions within it) and return a Promise and not a raw value you can omit the async keyword for it.

Alternatively you can go the full way with 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
    }
  }
}

1πŸ‘

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

Leave a comment