In JavaScript, async
is a keyword placed before a function to allow the function to return a promise. Since JavaScript is a synchronous language, Async functions let us write promise-based code as if it were synchronous, but without blocking the execution thread that allows the code to run asynchronously.
Async functions will always return a value. Using async implies that a promise will be returned. If a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.
Async is actually syntactic sugar built on top of promises. It was introduced to make asynchronous code look and behave a little more like synchronous code.
The following code example shows what an async
function looks like:
async function example(){return "Hello! This is asyncronous function."}
We can see that the async function is the same as the function that returns a promise, only easier to read:
function example(){return Promise.resolve("Hello! This is asyncronous function.")}
await
is another useful keyword that is often used alongside async functions. The keyword await
makes JavaScript wait until that promise settles and returns its result.
The following example shows how async/await
works:
function resolved() {return new Promise(resolve => {setTimeout(() => {resolve('resolved');}, 2000);});}async function example() {console.log('wait for 2 seconds...');const result = await resolved();console.log(result);//"resolved"}example();
The asynchronous function example()
runs, and the await
keyword lets the function know to wait for results from the promise inside resolved()
function. After 2 seconds, the function is resolved and our asynchronous function returns the result.