Home > Mobile >  How to make 2nd async method run after 1st async method has finished
How to make 2nd async method run after 1st async method has finished

Time:12-24

I have two async methods that I run in succession, but I need to 2nd method called to execute only after the 1st method has resolved

class Class {
  constructor() {}

  async foo() {
    setTimeout(() => {
      console.log(1);
    }, 2000);
  }

  async bar() {
    setTimeout(() => {
      console.log(2);
    }, 0);
  }
}

(async() => {
  const obj = new Class();
  await obj.foo();
  await obj.bar();
})()

The output of the above code:

> 2
> 1

What I need is for the output to be:

> 1
> 2

There's clearly some gaps in my knowledge regarding async/await functions.

Is it possible for me to achieve this? Because of my gap in knowledge, is there a reason I shouldn't be wanting this? Any helped would be much apprecaited.

CodePudding user response:

You need to return a custom promise that will resolve when the setTimeout finishes, you can't just use regular async functions. Like this:

class Class {
  constructor() {}

  foo() {
    return new Promise((resolve, reject) => setTimeout(() => {
      console.log(1);
      resolve();
    }, 2000));
  }

  bar() {
    return new Promise((resolve, reject) => setTimeout(() => {
      console.log(2);
      resolve();
    }, 0));
  }
}

(async() => {
  const obj = new Class();
  await obj.foo();
  await obj.bar();
})()

If you want to learn more about promises, then you might want to read this MDN article.

  • Related