Asynchronous progamming is a feature in which you don’t have to wait for a function execution to complete before going to your next command.

How can you run tasks in asynchronously in JavaScript?

The modern ways to run tasks asynchonously are :
Promises
CallBack
Async/Await

Using Promise for asynchronous programming

A promise is a function that takes another function (called executor function) as a parameter.
The executor function is the one that runs asynchronously.

This executor function takes two parameters (the parameters are also functions themselves):

  1. Function to be called when the Executor function completes succesfully (let's call it resolvedFunction)
  2. Function to be called when the Executor function encounters an error (let's call it rejectedFunction)

The executor function then calls one of these functions based on success/failure. If the executor function completes succesfully, it calls resolvedFunction() with the result you want to return from the asynchronous operation. If the executor function encounters error, you would typically call rejectedFunction with the error message.

The resolvedFunction and rejectedFunction are called only after the executor completes (in other words: after
the promise is settled)

Below is an example of how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var myPromise = new Promise((resolvedFunction,rejectedFunction)=>{
result = asynchronousOperation(); //Assume it is some long running task that returns an object with 'status' field
if(result.status == 'success'){
resolvedFunction(result);
}
else {
rejectedFunction("Error running the asynchronous operation");
}
});
myPromise.then((result)=>{//do something with the ressult}, (errorMessage)=>{//do something with the errorMessage});

/*
The line above gets executed only after the promise is settled. The remaining part of the code continues execution.
The function being executed currently cannot be interrupted just because an asynchronous function gets resolved.
*/

//remaining part of your code

Using CallBack for asynchronous programming

This video that I made explains how to use CallBack with an example.

CallBack is possibly the simplest way to implement asynchronous programming in JavaScript. A CallBack is a function that you provide inside another function as a parameter. Here is an example of how CallBack can be useful.
1
2
3
4
function getFile();
function useFIle();
var file = getFile();
useFile(file);

Sometimes functions like getFile() trigger getting file from a server and don’t wait for the file to be received. In such a case, useFile() would start executing before it gets the file and cause an error. We can solve this using CallBack. We can pass the useFile function inside getFile(). Then we can ensure that we call useFile only after the process of getting file is complete. It looks like this:

1
2
3
4
5
6
7
function getFile(callBack){
// code to get the get the file
useFile();
}
function useFile();
getFile(useFile);

async/await

Promise chains can be difficult to read. Look at this example. The .then() chains make it difficult to read:

1
2
3
4
5
6
7
8
9
10
11
12
13
async function returnsPromise1(parameter1){
result1 = APICall1(); //returns a promise
return result1;
}
// Now we call the function above and then call other async functions to use the result from previous calls.
returnsPromise1(parameter1).then((resolved1) =>{
return APICall2(resolved1); //returns a promise
}).then(resolved2 =>{
return APICall3(resolved2); //returns a promise
}).then(resolved3 =>{
APICall3(resolved3);
})

We see that this chaining can get difficult to read. Using async/await makes it more readable, as you see below.

1
2
3
4
5
6
7
8
9
async function returnsPromise1(parameter1){
result1 = APICall1(); //returns a promise
return result1;
}

const result1 = await returnsPromise1(parameter1);
const result2 = await APICall2(result1);
const result3 = await APICall3(result2);