1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, but because of Stimulus.js using a wrapper method is not an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.