Handling “A”-synchronousity in JS

📄 Table of Contents

History

Callbacks

How to define a custom callback

Passing a custom callback as an argument

The Fake Data Fetcher

Promises

Syntax

Basic Promises Syntax

◉ The Fake Data Fetcher (with Promises)

Basic Promise With A Single .then() Method

Basic Promises with a single then method

Promises With Multiple .then() Methods

.then method following a Promise constructor

.then() method following another ‘then’ returning a value/reference

Then methods executing synchronously (not recommended)

.then() method following another ‘then’ returning a Promise

Promise Chaining

Chaining promises

Explanation

Promise Pyramid or Nested Promises

Problem with promise chaining
Nested promises

Order of Execution of Promise Blocks

Order of execution of promise blocks

Catching errors in Promises

Promise.all() vs Promise.race()

Anti-patterns

Then methods with no-returns
Promise chaining with/without return statement

Note: Only in the promise constructor block you do not have to explicitly return a resolve/reject. Apart from that, in the consecutive then methods, every value and promise chained needs to be returned, for accessing it further down the block.

Bonus Coding Challenge

Conclusion

Async/Await

Async

async function myFunc() {
return 1
}
function foo() {
return Promise.resolve(1)
}

Await

same implementation using Promises & Async/await

setTimeout along with async-await

getJSONAsync().then( function(result) {
// Do something with result.
});
async function f() {

let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});

let result = await promise; // wait until the promise resolves (*)

alert(result); // "done!"
}

f();

Cases where Promises still scores over Async-await

[1]. Making multiple IN-dependent A-synchronous calls

async function getABC() {
let A = await getValueA(); // getValueA takes 2 second to finish
let B = await getValueB(); // getValueB takes 4 second to finish
let C = await getValueC(); // getValueC takes 3 second to finish
return A*B*C;
}
async function getABC() {
// Promise.all() allows us to send all requests at the same time.

let results = await Promise.all([ getValueA, getValueB, getValueC ]);
return results.reduce((total,value) => total * value);
}

[2]. Handling Errors in Async/Await

async-await using try-catch
async-await WITHOUT try-catch

Browser Support

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.