简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM