Skip to main content

Async and await

async keyword

async keyword is placed before a function like so:

async function f() {
	return 1;
}

It basically make your function always returns a promise. If you didn't return a promise explicitly in the function they will be wrapped in a resolved promise automatically. The above async function is equivalent to the one below:

function f() {
	return Promise.resolve(1);
}

Async function are thenable because they return a promise object:

async function f() {
	return 1;
}

f().then(console.log); // prints out 1

It just ensures that the returned value is a promise 100% and enables await in the function body, that is all. Function is still executed as a normal function!

await keyword

You can only use await inside an async function, using it outside of an async function will result in a syntax error

The keyword await will make JavaScript wait until that promise settles and return the result of the resolved promise object as the value:

async function f() {
	let promise = new Promise((res, rej) => {
    	setTimeout(() => res("done"), 1000)
	});
    
    let result = await promise;
    console.log(result); // prints out done!
}

f();

await basically makes the function wait at the promise that you used it on and wait until the promise settles before moving on.

It will wait for another promise to resolve before moving on with its own execution.

The waiting doesn't cost any extra CPU time because since the function is marked asynchronous it can move onto executing other part of the code before resuming the execution after the promise you are awaiting is resolved.

Using await is just a more elegant syntax of executing .then, you wait until the promise is resolved before moving on. It is easier to read and write.

But you can only use await in a async function!