An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
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
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
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;}
is the same as the normal function below that returns a promise.
async function One() { return Promise.resolve(1);}
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();
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
Original Link: https://dev.to/lindaojo/simple-explanation-of-async-await-in-javascript-199p
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To