Async, await, promises & callbacks in JavaScript
Promises : Courtesy to this medium article
Promises in javascript are very similar to promises made in real life. They can be kept & broken. If its kept we react differently & also when its not kept we react differently.
Promises has two parts :
1) Creating Promise
2) Handling Promise
Simple Example
let promise = new Promise(function(resolve, reject) { if(promise_kept) resolve("done"); else reject(new Error("…")); });
As it can be seen, Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.
Chaining Promises
A promise can be returned to another promise , creating a chain of promises. If one fails all others too.
new Promise(function(resolve, reject) { setTimeout(() => resolve(1), 1000); }).then(function(result) { alert(result); return result * 3; }).then(function(result) { alert(result); return result * 4; }).then(function(result) { alert(result); return result * 6; });
All of the operations return there results to the next then()
function on resolve and this process continues till the chain is
complete. The last element in the chain return the final result.
Async & Await : Courtesy to this medium article
What is Async & Await?
Async and Await are extensions of promises. Async functions enable us to write promise based code as if it were synchronous, but without blocking the execution thread.
async function firstAsync() { return 27; } firstAsync().then(alert); // 27
Running the above code gives the alert output as 27, it means that a promise
was returned, otherwise the .then()
method simply would not be possible.
Await : The await operator is used to wait for a Promise. It can be used inside
an Async block only. The keyword Await makes JavaScript wait until the
promise returns a result. 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 the use of Async Await together.
async function firstAsync() { let promise = new Promise((res, rej) => { setTimeout(() => res("Now it's done!"), 1000) }); // wait until the promise returns us a value let result = await promise; // "Now it's done!" alert(result); } }; firstAsync();
Important Node : We cannot use await inside normal function. The function must have async keyword if you want to use await.
Async & Await makes execution sequential. The below takes 100ms to complete :
async function sequence() { await promise1(50); // Wait 50ms… await promise2(50); // …then wait another 50ms. return "done!"; }
Another way of working with more then one promises :
async function sequence() { await Promise.all([promise1(), promise2()]); return "done!"; }
The promise.all()
function resolves when all the promises inside the iterable have been resolved and then returns the result.
Last Method :
async function parallel() { // Start a 500ms timer asynchronously… const wait1 = promise1(50); // …meaning this timer happens in parallel. const wait2 = promise2(50); // Wait 50ms for the first timer… await wait1; // …by which time this timer has already finished. await wait2; return "done!"; }
Now in this part of article we will see why do we even need Async & Await. Lastly we will build simple web app based on the concept we have learned so far.
Courtesy of this section goes to them
We need promises because nesting callbacks will soon look like :
When callbacks are nested in this way it becomes difficult to understand & debug the code. So here basically callbacks come in action.
Difference between Promises & Async / Await can be understood by below code :
// Async/Await const asyncGreeting = async () => 'Greetings'; // Promises const promiseGreeting = () => new Promise(((resolve) => { resolve('Greetings'); })); asyncGreeting().then(result => console.log(result)); promiseGreeting().then(result => console.log(result));
Now finally if you want to apply this knowledge practically then make sure to follow along with this article where you will learn how to create basic currency converter using Async / Await.
No comments:
If you have any doubt or suggestion let me know in comment section.