Async Await using TypeScript

  • The promise constructor takes one generic type for its resolved value. Let's use the number type for now.
  • The constructor takes an executor callback which will be called by the runtime with two arguments.
  • The first argument is a resolve function that can be used to resolve the promise.
  • The second argument is a reject function that can be used to reject the promise.
const example = new Promise<number>((resolve, reject) => {  // Use resolve or reject to determine the fate of the promise});example.then(value => console.log('then', value));
example.then(value => {  console.log('then', value);});example.catch(error => {  console.log('catch', error);});
  • If we resolve the promise, any then callbacks are executed.
resolve(123);
  • If we reject the promise, any catch callbacks are executed.
reject(new Error('failed'));// throw 'message' => bad// throw new Error('message');  => good

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store