Using the result of one function in another function when using async await

I am facing an issue with running a function based on the return value of another function:

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

Can someone guide me on how to achieve this? Since JavaScript is runtime, it does not wait for the result of funcOne(). I believe I should implement Promise or async/await, but I'm unsure of the correct approach.

UPDATE

After following the suggestions provided, I still couldn't get it to work. Let me explain the scenario:

I have integrated sweet alert functionality. If a confirmation is received from the sweet alert, an axios request should be sent. Here is the code snippet:

utils.js serves as a globally added mixins

async function sweetAlert(options) {
  // options: method('callback') , icon, title, text, callback, cValue
  if (options.method === 'confirm' || options.method === 'callback') {
    this.$swal({
      icon: options.icon,
      title: options.title,
      text: options.text,
      showCancelButton: true,
      cancelButtonText: this.lang.cancel,
      confirmButtonText: this.lang.confirm
    }).then(async (result) => {
      if (result.value) {
        if (options.method === 'callback') {
          let res = await options.callback(options.cValue)
          return res
        }

        return true
      }
    })
  }
}

Code snippet in my component script:

let res = await this.sweetAlert({
  method: ALERT_METHOD[2], // it is 'confirm'
  icon: ALERT_TYPE[2], // it is warning
  title: this.lang.deactivate, // added globally
  text: this.lang.deactivate_warning, // added globally
})

if (res) {
  this.activeSwitchDis = true // in my data
  this.activeChanged = true // in my data
  // this.axiosGet is a globally adde this.axios.get
  let response = await this.axiosGet(`product/deactive/${this.editProduct.pId}`)
  // this.resOk is globally added and check for 200
  if (this.resOk(response.status)) {
    // these are my data and funcs no prob with theme
    this.changeError(false)
    this.active = false
    this.activeChanged = false
    this.activeSwitchDis = false
    this.setEditProductActive(this.active)
  } else {
    // these are my data and funcs no prob with theme
    this.active = true
    this.activeChanged = false
    this.activeSwitchDis = false
  }
}

The issue lies in ensuring that the axios call is only made upon confirming the sweet alert.

Answer №1

When using JavaScript, it's important to note that since it is runtime, it won't wait for the result of the function funcOne().

In the context of your code example, if the funcOne() function is not asynchronous, the call will indeed wait for the function to complete and return its value.

If you're unsure about how to handle this situation and think you should be using Promise or async/await, I recommend checking out the documentation on Promises and async/await Syntax for functions for a better understanding.

Update

Regarding your code snippet: your implementation of sweetAlert() does not return anything because the return statements are scoped within 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
    })
  }
}

To properly capture the return value of the chain as the return value of sweetAlert(), you need to explicitly 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
    })
  }
}

It's worth noting that sweetAlert() will only return something if it enters the first if block. Additionally, if you don't use await directly in the sweetAlert() function and return a Promise instead of a raw value, you can omit the async keyword from the function.

Alternatively, you can opt for a full implementation 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
    }
  }
}

Answer №2

methods:{
  async actionOne(){
    // perform a task
    await executeAsyncTask();
    return true
  }
}


//inside component.vue
methods:{
  async actionTwo(){
    let result = await this.actionOne()
    if(result){
    // carry out an operation
    }else{
    // execute another operation
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting npm audit error involving loadVirtual and ENOLOCK

➜ npm safety check npm ERR! code ENOLOCK npm ERR! safety check This operation requires an existing lockfile. npm ERR! safety check Please generate one using: npm i --package-lock-only npm ERR! safety check Original error: loadVirtual needs a preexistin ...

How can you create an animation that plays forward on the first click and then reverses on the second

After coming across numerous similar questions, I realize that most of them refer to the outdated .toggle() function. My main challenge lies in achieving the desired effect where div#p moves right on the first click and then returns to its original positio ...

Having trouble with Isotope masonry functionality

While experimenting with Isotope from , I tested the reLayout method using the provided example found at . I copied the css and js to my page () but encountered an issue where clicking on the first element caused all other elements to move to the first col ...

Guide to Implementing <audio/> in a Nuxt-js Application

Storing my mp3 files and images under the static file, I have been able to access my images using the method below. However, I am facing difficulty in accessing my mp3 files. Despite making some adjustments in nuxt.config.js, I still cannot reach the mp3 f ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...

What is the process for encrypting a string in JavaScript?

Is there a simple way to hash a string in JavaScript without having to create the hashing algorithm myself? Are there any reliable npm packages or built-in functions available for this task? If so, how can I utilize them to hash a string? For instance, if ...

The three.js library encountered an ERROR 404 ( File Not Found ) when trying to import an existing file

Error: GET http://localhost:port/js/three net::ERR_ABORTED 404 (Not Found) I am currently working on a web development project using Three JS. I downloaded the master Zip of ThreeJS from the official website of Three JS I copied the JS files from the Bui ...

display a dropdown menu with a default selection

Trying to pre-select a value in a dropdown from database but facing issues. Need assistance in resolving this problem. HTML <select class="form-control" ng-model="reportType.consolidationScopeId"> <option value="">Please select</option& ...

Tips for utilizing the Ace editor validator without the need to create a new Ace editor instance

In my React application, I utilize react-ace to build a CSS text editor. The implementation looks something like this... import Ace from 'react-ace' ... <Ace mode="css" value={value} onChange={onValueChange} onValidate ...

The performance of dom-repeat may be impacted when dealing with sizable objects, such as those containing base64 encoded images

Currently, I am encountering an issue while generating a dom-repeat using a list of objects. Each object in the list has an imgUrl key containing a large base64 encoded image. However, when I generate the dom-repeat in this manner, each item appears undef ...

React fails to display image on the server

One issue I'm facing with my React project on the server is that some images are not being displayed. Click here to view image description The console error message reads: ASGimagen.png:1 GET https://[url of my server]/autodiagnostico/cuadroanimado ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Validation issue with Reactive Forms not functioning as expected

My latest project involves a user signup component that I created from scratch import { Component } from '@angular/core'; import {UserManagementService} from '../user-management.service'; import {User} from "../user"; import {FormBuild ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

Personalized JavaScript Arrays

Seeking assistance to format data received from an API. Can anyone provide guidance? fields: [ { name: "A", values: { data: [1, 2, 3, 4, 5] } }, { name: "B", values: { data: [6 ...

There seems to be a caching issue in ReactJS and Spring Data Rest that could be causing problems with

Encountering an unusual caching problem here. Just recently wiped out my database. While adding new users to the system, an old user mysteriously reappeared. This user has not been recreated and is not in the current database whatsoever. I'm at a lo ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

ParsleyJS always seems to miss the mark when it comes to

I had previously sought advice on a different JavaScript/jQuery form validation library but was told it was outdated, so I switched to Parsley. While Parsley allowed me to make some progress, I still encountered issues with its functionality. Specifically, ...

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

Getting attribute values from custom tags in AngularJS is a common task that can be

I am new to AngularJS and I'm having trouble with my code. I am attempting to retrieve the attribute value of post-id from my index.html file and display it in the console from my controller. Here is a snippet from my index.html: <post-creator po ...