Sandip Subedi
Sandip Subedi

Reputation: 1077

Multiple function call on button click synchronously with async-await not working

I am trying to figure out how to call multiple methods with 1 button click synchronously. My first function is an AJAX call. So it's naturally not synchronous. To solve that issue I have used async-await. Async-await is waiting inside the same function, but not on the other functions that are being called.

I am using Stimulus.js to create classes, but general answer is enough for me: https://stimulusjs.org/

This is what my code looks like:

Button: onClick:

classA#methodA classB#methodB

in class A

async methodA(event){
  const response = await axios.post('/url', { data }, options);
  const data = await response.json();
  doSomething()
}

in class B

methodB(){
  updateThings()
}

So what I want to achieve is classA#methodA classB#methodB be called synchronously. But methodA is not waiting for methodB even though methodA is not compete. And even when I am using async await on methodA.

Any idea on how I can solve this issue?

Creating a wrapper method and calling them doesn't seem possible because of the way Stimulus.js works.

Upvotes: 1

Views: 1609

Answers (1)

Felipe Jacob
Felipe Jacob

Reputation: 394

In your button click, you should have something like that:

async () => {
    await methodA();
    await methodB();
}

And also, the both methods should have the async mark:

async methodA(event){
  const response = await axios.post('/url', { data }, options);
  const data = await response.json();
  doSomething()
}

async methodB(){
  updateThings()
}

As your methodA is async, the main call to this method by default won't wait it to finish before executing the next lines. So you should explicitly say await methodA().

Check it out: Understanding async await in javascript

Upvotes: 1

Related Questions