Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'await' inside a sync function?

Tags:

typescript

I want to make an API like this:

class jsonReader {
  public async load()
  {
     // some code
  }
}

let reader = new jsonReader();

function foo(){
  await reader.load();
  // [ts] 'await' expression is only allowed within an async function.
}

How can I use Async/Await inside a synchronous function call?

like image 421
kalpa Avatar asked Apr 29 '26 02:04

kalpa


1 Answers

You either make that function asynchronous as well and use await or use the promise from the returned function. All functions marked with async return Promise<T>. In your shared code the return type is Promise<void>, you can chain then to it.

function foo(){
  reader.load().then(() => /*your code here*/);
}
like image 153
Igor Avatar answered Apr 30 '26 15:04

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!