JavaScript Asynchronous

wahyu eko hadi saputro
4 min readJun 5, 2022

For programmers we must be familiar with asynchronous terms. On the wikipedia, Asynchronous, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. In nutshell asynchronous is not serial or sequence of activities, for example :

we want to make a cup of tea, the activities are :a. Boiling water
b. Put tea on a glass
c. Put some sugar on a glass
d. Pouring hot water on a glass
e. Mix the water in the glass with a spoon

All of the above activities can be done in an asynchronous way, though, so that while boiling water we can put some tea and some sugar on the glass, then after the water is boiled, we can start pouring water into the glass, then just mix everything inside the glass with a spoon.

In javascript we can achieve asynchronous with many ways:
a. Asynchronous with callback
b. Asynchronous with promise
c. Asynchronous with async / await

A. Asynchronous with callback

setTimeout(function() { myFunction("test callback async !!!"); }, 3000);
function myFunction(value) {
console.log(value)
}

Based on the code above, we use myFunction as a callback, so that text “test callback async !!!” will be printed on the console log after 3000 ms. Usually a callback function is used to call REST API, so the response data will be presented on the screen when the API response is successfully received by the client. Example :

function callDummyAPI(myCallback) {
fetch("https://catfact.ninja/breeds")
.then(response => response.json())
.then(json => printData(json))
.catch(error => {
// handle the error
console.log(error)
});
}
function printData(value) {
console.log(value);
}

callDummyAPI(printData)

The explanation of the above code is that we use printData as the callback function, and we pass printData as the argument of method callDummyAPI. Method printData will be executed after API response is completely received by the client (javascript code).

B. Asynchronous with promise

Promise in javascript are kind of hard to master. Promise is a wrapper for async processes, and promise more advanced than async with callbacks.

There are 3 states of promise.
While a Promise object is “pending” (working), the result is undefined.
When a Promise object is “fulfilled / resolved”, the result is a value.
When a Promise object is “rejected”, the result is an error object.

We can illustrate the flow promise like this: You want to eat banana cake, and you ask your little brother to buy it. The time while waiting for your little brother to buy banana cake is called pending state and at that time you can do another activities like cleaning the room, reading and so on. The state when your little brother is able to hand over banana cake to you is called a “resolved” state and otherwise, when the cake is run out it means your little brother can not fulfill the order it is called rejected state.

Fulfilled / resolved promise

const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hi promise thread');
}, 3000);
});

myPromise.then(
function(value) {console.log(value);}
).catch(error => {
console.log('Request failed', error);
});
console.log("main thread");

If the promise is in resolved state the .then(function(value) {console.log(value);} will be executed

Rejected promise

const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject('hi promise thread');
}, 3000);
});

myPromise.then(
function(value) {console.log(value);}
).catch(error => {
console.log('Request failed', error);
});
console.log("main thread");

If the promise is in rejected state the .catch(.. Code will be executed

C. Asynchronous with Async/Await

Await keyword will wait until a promise return value (resolved / rejected). And await only can be used inside the Async keyword. Async/Await is just a wrapper of promise to ease programmers to do async code.

const myPromise = () => {
return new Promise(resolve => {
setTimeout(() => resolve('hi promise'), 3000)
})
};
const callMypromise = async () => {
const something = await myPromise()
return something + ' , i am calling you'
};

callMypromise().then(res => {
console.log(res)
}).catch(error => {
console.log('Request failed', error);
});

console.log("main thread");

Based on the above code, we can see chain of asynchronous execution (promise). The main thread console.log(“main thread”), is executed first while waiting for the promise. At the first state, the promise is in pending state and after 3000 ms the promise is resolved then represents “hi, promise .. “ on the browser.


async function myFunction(){
try{
ddddd("go");
}catch(err){
console.log(err);
}
bbb("go");
return "I love You !!";
}

async function myDisplay() {
console.log("hi")
await myFunction().then(
function(value) { console.log(value) },
function(error) { /* code if some error */ }
);

console.log("hi1")
}

myDisplay();

Source :

https://www.freecodecamp.org/news/what-is-promise-in-javascript-for-beginners/

https://www.w3schools.com/js/js_promise.asp

https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await

--

--