Callback, Promise and Async-await example in Javascript.

Bittu Kumar
5 min readSep 6, 2023

--

We have seen many different explanation of callback in javascript, but This time we will learn more with example and less with definition. I have collected many different example for learning and together with that you can practice the same to gain confidence.

We will cover list of concepts mentioned below

  • Callback
  • Callback Hell
  • Promise
  • Promise Chain
  • Async — await

callback, promise and async-await are the way to execute javascript in asynchronous way.

Callback- It is a function which is passed as a argument of another function.

Promise-

It is an object representing the completion or failure of an asynchronous task. It is used to avoid the callback hell and makes our code more readable. It has three state- pending, resolve and reject.

Async-await-

It is again a way to handle asynchronous operation in javascript. It is modern syntax of handling asynchronous task. It is extension of promise that makes our code easier to read and write. The async keyword is used before the function declaration where we have to execute asynchronous task and it return a promise. Await keyword is used inside the async function where we need to pause the execution until the promise is resolved.

Example 1: (callback)

function getUser(callback){
const user= {id: 123, name: "john"};
callback(user);
}
getUser(function(user){
console.log(user);
})

// output: {id: 123, name: "john"}




// example

function calc(a,b,method){
return method(a,b);
}

function add(a,b){
return a+b;
}

function subs(a,b){
return a-b;
}

console.log(calc(2,3,add))
console.log(calc(4,3,subs))

// 5
// 1

Example 2 : (callback)

//we have list of users:
const usersDatabase = [
{ id: 123, name: "Bittu" },
{ id: 456, name: "Ravi" },
{ id: 789, name: "vivek" },
];

// get user details
// input=> id:4 -> output (id: 4,name:"bittu") -- complete object

function getUser(userId, callback){
let user;
usersDatabase.forEach((data)=>{
if(data.id===userId){
user= data;
}
})

if(user){
callback(user);
}
else{
callback(null)
}
}

getUser(123,function(user){
if(user){
console.log(user);
}
else{
console.log("user not found")
}
})

//output: {id: 123, name: "Bittu"}
// try passing some different id which is not present in array of object in getUser method



//other example
function getUser(id, cb){
setTimeout(() => {
console.log("reading data");
const user= {id, name: `User ${id}`};
console.log('before callback function called')
cb(user);
console.log('after callback function called')
}, 2000);
}

getUser(1, function user(user){
console.log(user)
});

Example 3: (callback hell)

const usersDatabase = [
{ userId: 123, name: "Bittu" },
{ userId: 456, name: "Ravi" },
{ userId: 789, name: "Vivek" },
];

const orderDetailsDatabase = [
{ orderId: 101, userId: 123, items: ['burger', 'fries', 'coke'] },
{ orderId: 102, userId: 456, items: ['burger', 'fries', 'coke'] },
{ orderId: 103, userId: 789, items: ['burger', 'fries', 'coke'] },
];

const orderStatusDatabase = [
{ orderId: 101, cookedStatus: 'ready' },
{ orderId: 102, cookedStatus: 'notReady' },
{ orderId: 103, cookedStatus: 'ready' },
];


// input: id --> getUserDetails --> output: userId, name
// input: userId --> getOrderDetails --> output: orderId,items
// input: orderId --> getOrderStatus --> output: cookedStatus




function getUserDetails(id, callback) {
let user;
console.log("input id: ", id)
usersDatabase.forEach((data) => {
if (data.userId === id) {
user = data;
}
})
console.log("user", user)
callback(user);
}

function getOrderDetails(orderId, callback) {
let orderDetails;
orderDetailsDatabase.forEach((data) => {
if (data.userId === orderId) {
orderDetails = data;
}
})
console.log("order", orderDetails)
callback(orderDetails)
}

function getOrderStatus(orderId) {
let orderStatusDetails;
orderStatusDatabase.forEach((data) => {
if (data.orderId === orderId) {
orderStatusDetails = data;
}
})
console.log("Order Status", orderStatusDetails)
}




getUserDetails(123, function (user) {
getOrderDetails(user.userId, function (orders) {
getOrderStatus(orders.orderId)
})
})

// output--
// input id: 123
// user: {userId: 123, name: "Bittu"}
// order: {orderId: 101, userId: 123, items:["burger", "fries", "coke"]}
// Order Status: {orderId: 101, cookedStatus: "ready"}

Example 4: (callback with setTimeout function)

const usersDatabase = [
{ userId: 123, name: "Bittu" },
{ userId: 456, name: "Ravi" },
{ userId: 789, name: "Vivek" },
];


function getUserDetails(id, callback) {
setTimeout(function () {
let user;
usersDatabase.forEach((data) => {
if (data.userId === id) {
user = data;
}
})
callback(user)
}, 3000)
}


getUserDetails(123, function (user) {
console.log("user id: ", user)
})

// user id : {userId: 123, name: "Bittu"}

Example 5: (callback hell with setTimeout function)

//we have list of users:
const usersDatabase = [
{ userId: 123, name: "Bittu" },
{ userId: 456, name: "Ravi" },
{ userId: 789, name: "Vivek" },
];

const orderDetailsDatabase = [
{ orderId: 101, userId: 123, items: ['burger', 'fries', 'coke'] },
{ orderId: 102, userId: 456, items: ['burger', 'fries', 'coke'] },
{ orderId: 103, userId: 789, items: ['burger', 'fries', 'coke'] },
];

const orderStatusDatabase = [
{ orderId: 101, cookedStatus: 'ready' },
{ orderId: 102, cookedStatus: 'notReady' },
{ orderId: 103, cookedStatus: 'ready' },
];


// input: id --> getUserDetails --> output: userId, name
// input: userId --> getOrderDetails --> output: orderId,items
// input: orderId --> getOrderStatus --> output: cookedStatus




function getUserDetails(id, callback) {
setTimeout(function () {
let user;
console.log("input id: ", id)
usersDatabase.forEach((data) => {
if (data.userId === id) {
user = data;
}
})
console.log("user", user)
callback(user);
}, 2000)
}

function getOrderDetails(orderId, callback) {

setTimeout(function () {
let orderDetails;
orderDetailsDatabase.forEach((data) => {
if (data.userId === orderId) {
orderDetails = data;
}
})
console.log("order", orderDetails)
callback(orderDetails)
}, 5000)
}

function getOrderStatus(orderId) {
setTimeout(function () {
let orderStatusDetails;
orderStatusDatabase.forEach((data) => {
if (data.orderId === orderId) {
orderStatusDetails = data;
}
})
console.log("Order Status", orderStatusDetails)
}, 3000)
}


getUserDetails(123, function (user) {
getOrderDetails(user.userId, function (orders) {
getOrderStatus(orders.orderId)
})
})

// output-
// input id: 123
// user: {userId: 123, name: "Bittu"}
// order: {orderId: 101, userId: 123, items:["burger", "fries", "coke"]}
// Order Status: {orderId: 101, cookedStatus: "ready"}

Example 6 : (asynchronous JS for practice)


// *******
console.log("first");

setTimeout(function(){
console.log("second");
});

console.log("third")


// first
// third
// second


// now we want to print first,second,third in this order
// doesn't matter how much time this setTimeout takes


console.log("first");

function test(callback){
setTimeout(function () {
console.log("second");
callback()
}, 1000);

}

test(function(){
console.log("third")
})


Example 7 : (Simple Promise )

const myPromise = new Promise((resolve, reject) => {
const randomNum = Math.round(Math.random() * 10);
if (randomNum < 5) {
resolve(`Success! Random number: ${randomNum}`);
}
else {
reject(`Error! Random number: ${randomNum}`);
}
});

myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});

Example 8: (Promise with setTimeout)

const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNum = Math.round(Math.random() * 10);
if (randomNum < 5) {
resolve(`Success! Random number: ${randomNum}`);
}
else {
reject(`Error! Random number: ${randomNum}`);
}
}, 1000);
});

myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});

Example 9: ( Promise — Fetch API)

function fetchData(url) {
return fetch(url);
}

const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';

fetchData(apiUrl)
.then(response => {
return response.json();
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.log('Error:', error);
});

Example 10: (async - await)

const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';


async function fetchData11(url) {
try {
const response = await fetch(url);
const data = await response.json();
console.log('Data received:', data);
} catch (error) {
console.log('Error:', error);
}
}

fetchData11(apiUrl);

Thanks for reading it out completely.

Happy learning !!

--

--

Bittu Kumar
Bittu Kumar

Written by Bittu Kumar

Exploring Angular and Frontend development.

No responses yet