Ronaldo Vitto Lewerissa

Software engineering learning documentation.

Brief Note on JavaScript Promises and Async/Await

Promise has the following syntax:

new Promise((resolve, reject) => {  
  // code goes here...
});

Invoking resolve() will returns a resolved promise.

let resolvedPromise = new Promise((resolve, reject) => resolve());  

Invoking reject() will returns an rejected promise.

let resolvedPromise = new Promise((resolve, reject) => reject());  

Throwing an error inside a .then will returns a rejected promise:

  Promise.then(() => throw new Error());

.then() will be executed if prior promise resolves, returns a rejected promise if prior promise is rejected.

.catch() will be executed if prior promise rejected, returns a resolved .

An unhandled rejected promise will not stop execution context from running, and is not handled the way normal throws (in try catch block).

Async function must yield (await) a promise!

Invoking an async function will returns a promise that resolves when the async function returns (pop), resolved with the returned value from the async function itself.

async().then((resolvedVal) => console.log(resolvedVal))  

If the returned is a promise, then it will resolved when the returned promise as in:

.then(() => new Promise((res, rej) => 2))

If none is explicitly returned, then it returns undefined as the resolved value.

Async functions are generators, which means it yields, where yield is equivalent to await. And it must yield a promise.

If the yielded promise resolves, it will continue executing the async function and pass along the resolved value back to it.

If it yields a promise that is rejected, the async function will returns with a rejected promise.

I currently have no idea how a async as a generator knows when it is done internally. What I mean is:

async function a() {  
  await new Promise((resolve, reject) => resolve());
  console.log('foo');
}
a().then((res) => console.log('bar'));  

This will outputs foo and bar respectively.

I was thinking that when it yields an object where .done() is true, then the async function will resolved, but apparently that is not the case.

Written by Ronaldo Vitto Lewerissa

Read more posts by this author.