In this article, we will be looking at async
keyword in javascript with examples. async
is used with functions in javascript.
function
keyword and is invoked using the name of function. Example,
// define function function printMessage() { document.write('Hello World!'); } // call function printMessage();
Above code defines a function and then invokes it. This will print
Hello World!
Nothing special till this point.
async function
A function definition preceded with async
keyword becomes an asyc function.
Unlike a normal function which returns the value, an async function returns a javascript promise .
This promise is in fulfilled state and wraps the value returned by the function. async function is invoked in the same way as normal functions.
If you print the value returned by an async function, then it will be a promise as shown below.
// define an async function async function getMessage() { return "Learning js"; } console.log(getMessage());
This prints
Promise {<fulfilled>: “Learning js”}
async function always returns a promise by default. This promise contains the actual value returned by the function which can be retrieved using
then()
method of the promise.Example,
// define an async function async function getMessage() { return "Learning js"; } // invoke function and get result getMessage().then(function(val) { document.write(val) });
Above code defines an async function and invokes it.
This function is guaranteed to return a promise. Notice how the returned value is retrieved using then()
method.
then()
accepts a callback function as argument. This callback function takes a single argument which contains the value returned by the promise.
Callback function can also be written as an arrow function as shown below
getMessage().then(val => { document.write(val) });
A normal function can be converted to an async function if it returns a promise.
Thus, below function is the same as an async function.
function getMessage(){ return new Promise((resolve, reject)=>{ resolve('Learning js'); }); }
or more concisely
function getMessage(){ return Promise.resolve('Learning js'); }
An async function can be assigned to a variable and this syntax is called function expression.
A function expression is invoked using the variable to which the function is assigned. Example,
// async function expression let m = async function getMessage() { return "Learning js"; }
It can be shortened using an arrow function as
// async function expression as arrow function let m = async () => { return "Learning js"; }
A function expression can be invoked as
m().then(val => document.write(val));
Hope the article was useful. Hit the clap below if was.