Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 1, 2021 12:05 pm GMT

Simple Explanation of Async-Await in Javascript

This was orginally posted at lindaojo.com

To fully appreciate the use of Async-Await you must first understand that by default, JavaScript is synchronous.

Synchronous Functions

In synchronous functions, operations run simultaneously and you can't specify pausing or waiting points.

Example

function solveC() {    const A = 1;    const B = 2;    const C = A + B;    return C;}console.log(solveC()); // 3
Enter fullscreen mode Exit fullscreen mode

But if for some reason there is a delay in getting the value 'B', JavaScript will execute other lines of code that aren't delayed. This could result in an error.

In the example below, 'B' is delayed. Let's check out what the results will be.

function solveC() {    const getB = () => {        setTimeout(() => {return 2;}, 500);     }    const A = 1;    const B = getB();    const C = A + B;    return C;}console.log(solveC()); // NaN
Enter fullscreen mode Exit fullscreen mode

What do we do to get the right result even if B is delayed? How do we ask Javascript to pause and wait for 'B'.

The answer is we make the function asynchronous. This is where "async-await" comes in.

Note: there are other ways to write asynchronous code. You could use Callback functions and promises.

Asynchronous Functions using Async-Await

To make a function Asynchronous we declare the function using the "Async" keyword.
The word async before a function means the function will always returns a promise.

The async function below...

async function One() {  return 1;}
Enter fullscreen mode Exit fullscreen mode

is the same as the normal function below that returns a promise.

async function One() {  return Promise.resolve(1);}
Enter fullscreen mode Exit fullscreen mode

We can ask JavaScript to wait for a promise by using the "await" keyword. It has to be noted that it only makes the async function block wait and not the whole program execution.

The code block below shows how we solve our earlier problem with the use of async-await.

async function solveC() {    function getB () {        setTimeout(() => {return 2;}, 100);     }    const A = 1;    const B = await getB();    const C = A + B;}solveC();
Enter fullscreen mode Exit fullscreen mode

Note: the "await" keyword can only be used within "async" functions.

That's it! Hope this was helpful cause I kept it light for beginners. If you want to read a more advanced explanation of async-await, I recommend this article by Ashay Mandwarya

Read more of my articles


Original Link: https://dev.to/lindaojo/simple-explanation-of-async-await-in-javascript-199p

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To