简体   繁体   中英

typescript awaiting an async function that returns a Promise<void>

Method() {
    // simulating a method of a third-party library that returns Promise<void>
    return new Promise(() => {
      // some time-consuming operations
    }).then(() => console.log('end'))
  }

Do we have to use await keyword when calling asynchronous methods that are not returning any data?

await this.Method().then(() => console.log('done'))
// or
this.Method().then(() => console.log('done'))

for this example is it guaranteed that all operations inside the Method() are completed before console prints " done " in both cases (using and not using await keyword)?

Is it guaranteed that all operations inside the Method() are completed before the .then() callback prints "done"

Yes, by the virtue of using the .then() method . The await keyword doesn't matter here. It does matter when you're doing

await this.Method();
console.log('done');

(which you probably should ).

Do we have to use await keyword when calling asynchronous methods that are not returning any data?

Yes, because they may still throw an error, and you want to wait for the completion even if you don't care about the return value. See Can I fire and forget a promise in nodejs (ES7)? for more discussion.

You can simply do as follows:

caller = await this.Method().then(() => console.log('done'))

or, if you don't need to use the result

caller = this.Method()

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