• Login
Sunday, June 1, 2025
Blogue
  • Homepage
  • Web
    The WordPress Drama- Open Source at War

    The WordPress Drama: Open Source at War

    The Plan to Break Apart Google- RIP Chrome_

    The Plan to Break Apart Google: RIP Chrome?

    Andrew Tate’s Hustler’s University Hacked- What We Know

    Andrew Tate’s Hustler’s University Hacked: What We Know

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Git : Developer’s Favourite

    Git : Developer’s Favourite

    HTTP Status/Error Codes and How to Fix them

    HTTP Status/Error Codes and How to Fix them

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    Guide to Googling

    Guide to Googling

    How To Submit a Form With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

  • Web Developer
    How to Detect Ad Blockers in a React.js Application

    How to Detect Ad Blockers in a React.js Application

    How to Create Responsive Image in CSS

    How to Create Responsive Image in CSS

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    How To Take Screenshot With Puppeteer

    How To Take Screenshot With Puppeteer

    Web Scraping With JavaScript and Puppeteer

    Web Scraping With JavaScript and Puppeteer

    How to create a Responsive Website

    How to create a Responsive Website

    Top Frontend Frameworks To Learn

    Top Frontend Frameworks To Learn

    Full Stack Web Developer: A Guide to Learn

    Full Stack Web Developer: A Guide to Learn

  • Web Scraping
    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Table Data into JSON File with Puppeteer

    Scraping Table Data into JSON File with Puppeteer

    How To Scrape Multiple Pages With Puppeteer and JavaScript

    How To Scrape Multiple Pages With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

    How to Automate Form Submission with Puppeteer and Javascript

    How to Automate Form Submission with Puppeteer and Javascript

    How To Take Screenshot With Puppeteer

    How To Take Screenshot With Puppeteer

    Web Scraping With JavaScript and Puppeteer

    Web Scraping With JavaScript and Puppeteer

  • How To?
    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    Facebook: The Engine Behind the World’s Largest Social Network

    Facebook: The Engine Behind the World’s Largest Social Network

    Snapchat: The System Powering Snaps, Stories, and Lenses

    Snapchat: The System Powering Snaps, Stories, and Lenses

    How WhatsApp Powers Instant Communication for Billions

    How WhatsApp Powers Instant Communication for Billions?

    How Instagram Scales to Billions of Photos and Videos Daily

    How Instagram Scales to Billions of Photos and Videos Daily?

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    Effective Structure for Describe Image, Retell Lecture, and Summarize Spoken Text in PTE Academic

    Effective Structure for Describe Image, Retell Lecture, and Summarize Spoken Text in PTE Academic

    Understanding Marks Allocation in PTE Academic Tasks

    Understanding Marks Allocation in PTE Academic Tasks

    From Power-On to Productivity: How Your Operating System Comes to Life

    From Power-On to Productivity: How Your Operating System Comes to Life

  • Technology
    A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs

    A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    The WordPress Drama- Open Source at War

    The WordPress Drama: Open Source at War

    25 Software Bugs That Changed the World

    25 Software Bugs That Changed the World

    The Plan to Break Apart Google- RIP Chrome_

    The Plan to Break Apart Google: RIP Chrome?

    Guide to Googling

    Guide to Googling

    How Video Streaming on the Internet Works

    How Video Streaming on the Internet Works

    Git : A short history

    Git : A short history

    A Walkthrough to Blockchain

    A Walkthrough to Blockchain

  • System Design
    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    Facebook: The Engine Behind the World’s Largest Social Network

    Facebook: The Engine Behind the World’s Largest Social Network

    Snapchat: The System Powering Snaps, Stories, and Lenses

    Snapchat: The System Powering Snaps, Stories, and Lenses

    How WhatsApp Powers Instant Communication for Billions

    How WhatsApp Powers Instant Communication for Billions?

    How Instagram Scales to Billions of Photos and Videos Daily

    How Instagram Scales to Billions of Photos and Videos Daily?

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How YouTube Handles Billions of Videos Daily

    How YouTube Handles Billions of Videos Daily?

    How Spotify Streams Personalized Music to Millions in Real-Time?

    How Spotify Streams Personalized Music to Millions in Real-Time?

Submit Post
No Result
View All Result
  • Homepage
  • Web
    The WordPress Drama- Open Source at War

    The WordPress Drama: Open Source at War

    The Plan to Break Apart Google- RIP Chrome_

    The Plan to Break Apart Google: RIP Chrome?

    Andrew Tate’s Hustler’s University Hacked- What We Know

    Andrew Tate’s Hustler’s University Hacked: What We Know

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Git : Developer’s Favourite

    Git : Developer’s Favourite

    HTTP Status/Error Codes and How to Fix them

    HTTP Status/Error Codes and How to Fix them

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    Guide to Googling

    Guide to Googling

    How To Submit a Form With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

  • Web Developer
    How to Detect Ad Blockers in a React.js Application

    How to Detect Ad Blockers in a React.js Application

    How to Create Responsive Image in CSS

    How to Create Responsive Image in CSS

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    A Walkthrough to Hashing, Salting , and Verifying Passwords in NodeJS, Python, Golang, and Java

    How To Take Screenshot With Puppeteer

    How To Take Screenshot With Puppeteer

    Web Scraping With JavaScript and Puppeteer

    Web Scraping With JavaScript and Puppeteer

    How to create a Responsive Website

    How to create a Responsive Website

    Top Frontend Frameworks To Learn

    Top Frontend Frameworks To Learn

    Full Stack Web Developer: A Guide to Learn

    Full Stack Web Developer: A Guide to Learn

  • Web Scraping
    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Websites with Various Scraper Frameworks (With Examples)

    Scraping Table Data into JSON File with Puppeteer

    Scraping Table Data into JSON File with Puppeteer

    How To Scrape Multiple Pages With Puppeteer and JavaScript

    How To Scrape Multiple Pages With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

    How To Submit a Form With Puppeteer and JavaScript

    How to Automate Form Submission with Puppeteer and Javascript

    How to Automate Form Submission with Puppeteer and Javascript

    How To Take Screenshot With Puppeteer

    How To Take Screenshot With Puppeteer

    Web Scraping With JavaScript and Puppeteer

    Web Scraping With JavaScript and Puppeteer

  • How To?
    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    Facebook: The Engine Behind the World’s Largest Social Network

    Facebook: The Engine Behind the World’s Largest Social Network

    Snapchat: The System Powering Snaps, Stories, and Lenses

    Snapchat: The System Powering Snaps, Stories, and Lenses

    How WhatsApp Powers Instant Communication for Billions

    How WhatsApp Powers Instant Communication for Billions?

    How Instagram Scales to Billions of Photos and Videos Daily

    How Instagram Scales to Billions of Photos and Videos Daily?

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    Effective Structure for Describe Image, Retell Lecture, and Summarize Spoken Text in PTE Academic

    Effective Structure for Describe Image, Retell Lecture, and Summarize Spoken Text in PTE Academic

    Understanding Marks Allocation in PTE Academic Tasks

    Understanding Marks Allocation in PTE Academic Tasks

    From Power-On to Productivity: How Your Operating System Comes to Life

    From Power-On to Productivity: How Your Operating System Comes to Life

  • Technology
    A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs

    A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    The WordPress Drama- Open Source at War

    The WordPress Drama: Open Source at War

    25 Software Bugs That Changed the World

    25 Software Bugs That Changed the World

    The Plan to Break Apart Google- RIP Chrome_

    The Plan to Break Apart Google: RIP Chrome?

    Guide to Googling

    Guide to Googling

    How Video Streaming on the Internet Works

    How Video Streaming on the Internet Works

    Git : A short history

    Git : A short history

    A Walkthrough to Blockchain

    A Walkthrough to Blockchain

  • System Design
    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    How LinkedIn Powers Professional Networking: A Look Inside Its System Design

    Facebook: The Engine Behind the World’s Largest Social Network

    Facebook: The Engine Behind the World’s Largest Social Network

    Snapchat: The System Powering Snaps, Stories, and Lenses

    Snapchat: The System Powering Snaps, Stories, and Lenses

    How WhatsApp Powers Instant Communication for Billions

    How WhatsApp Powers Instant Communication for Billions?

    How Instagram Scales to Billions of Photos and Videos Daily

    How Instagram Scales to Billions of Photos and Videos Daily?

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How Netflix Delivers High-Quality Streaming to Millions Worldwide

    How YouTube Handles Billions of Videos Daily

    How YouTube Handles Billions of Videos Daily?

    How Spotify Streams Personalized Music to Millions in Real-Time?

    How Spotify Streams Personalized Music to Millions in Real-Time?

Submit Post
No Result
View All Result
Blogue
  • Homepage
  • Web
  • Web Developer
  • Web Scraping
  • How To?
  • Technology
  • System Design

JavaScript Promises, Callbacks, and Async/Await

The Blogue Team by The Blogue Team
June 28, 2020
in Coding, ES6, JavaScript, Programming, Tutorial
Reading Time: 7 mins read
288
A A
0
307
SHARES
1k
VIEWS
Share on FacebookShare on XShare on RedditShare on Whatsapp

ES6 came with many new features, but one of the best features was the official introduction of Promises. Promises allow you to write clean non-callback-centric code without ever having to worry about callback hell. Even if you never write your own promise, knowing how they work is incredibly important, since many newer parts of the JavaScript API use promises instead of callbacks. The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:

  • pending — The initial state of a promise.
  • fulfilled — The state of a promise representing a successful operation.
  • rejected — The state of a promise representing a failed operation.

A promise in JavaScript is the same promise that we make in our life. If I promise to do something for a friend then it has two results. If I fulfill that promise by working on it then he will be happy or say it’s resolved in terms of Javascript. And if the promise is never fulfilled by me then I failed to keep my promise or let’s say it’s not resolved in terms of JavaScript cause it’s been rejected to be done.

Let’s take an example:

First, we will look into the example which gets resolved,

let p = new Promise ((resolve,reject)=>{
    let a = 1+1;
    if(a ==2){
    resolve('Succeded')
    }
else
    {
    reject('Failed')
}
})
p.then((message)=>{
    console.log('Its resolved and '+message)
})
.catch((message)=>{
    console.log('Its rejected and '+message)
})

Here, we create two-parameters inside the object of Promise(resolve, reject). We take ‘a’ as a promise and check whether it’s fulfilled or not. Line 11, we create “.then” which will call the message inside “resolve”. If we run the code then the condition is true because “promise a” value will be true i.e ‘a value equals to 2′. Since the condition gets satisfied We will get the message from ‘resolve’.

Another example which shows promise not being resolved,

Here, we create two-parameters inside the object of Promise(resolve, reject). We take ‘a’ as a promise and check whether it’s fulfilled or not. Line 11, we create “.then” which will call the message inside “resolve”. If we run the code then the condition is true because “promise a” value will be true i.e ‘a value equals to 2′. Since the condition gets satisfied We will get the message from ‘resolve’.

Another example which shows promise not being resolved,

Here, we create two-parameters inside the object of Promise(resolve, reject). We take ‘a’ as a promise and check whether it’s fulfilled or not. Line 11, we create “.then” which will call the message inside “resolve”. If we run the code then the condition is true because “promise a” value will be true i.e ‘a value equals to 2′. Since the condition gets satisfied We will get the message from ‘resolve’.

Another example which shows promise not being resolved,

let p = new Promise ((resolve,reject)=>{
    let a = 1+2;
    if(a ==2){
    resolve('Succeded')
}
    else
    {
    reject('Failed')
    }
})
p.then((message)=>{
    console.log('Its resolved and '+message)
}).catch((message)=>{
    console.log('Its rejected and '+message)
})

Here, we create two-parameters inside the object of Promise(resolve, reject). We take ‘a’ as a promise and check whether it’s fulfilled or not. Line 11, we create “.catch” which will call the message inside “reject”. If we run the code then the condition is false because “promise a” value will not be true i.e ‘a value not equals to 2’. Since the condition gets satisfied We will get the message from ‘reject’.

Callbacks:

A callback is a function called at the completion of a given task; this prevents any blocking and allows other code to be run in the meantime. Callbacks are the foundation of Node.js.Callbacks give you an interface with which to say, “and when you’re done doing that, do all this.” This allows you to have as many IO operations as your OS can handle happening at the same time. For example, in a web server with hundreds or thousands of pending requests with multiple blocking queries, performing the blocking queries asynchronously gives you the ability to be able to continue working and not just sit still and wait until the blocking operations come back.

Example of Callbacks:

function watchSuitsCallback(callback,errorCallback) {
   let userLeft = falselet userWatchingSuits = falseif (userLeft) {
        errorCallback({name: 'Episode completed', 
          message: 'Shit'})
          } 
    else if (userWatchingSuits) {
        errorCallback({
          name: 'User Watching Suits',
          message: 'With Harvey' 
        })
      } else {
        callback('Awesome')
      }
}
  
watchSuitsCallback(message => {
    console.log(message)
  },error => {
    console.log(error.name + ' ' + error.message)
})

Here, We are using a very simple callback function which takes two callbacks i.e one for success and another is for error. Here the function checks whether two variables are true or not. If it’s true then the callback will be for ‘success’ message else it will call ‘error’ message.

Now we will take the same example using promises:

function watchSuitsPromise() {
    let userLeft = falselet userWatchingSuits = falsereturn new Promise((resolve, reject) => {
  if (userLeft) {
        reject({
          name: 'Episode completed', 
          message: 'Shit'
        })
      } 
  else if (userWatchingSuits) {
        reject({
          name: 'User Watching Suits',
          message: 'With Harvey' 
        })
     } 
  else {
        resolve('Awesome')
      }
    })
}
watchSuitsPromise().then(message => {
    console.log(message)
  }).then(message => {
    console.log(message)
  }).then(message => {
    console.log(message)
  }).catch(error => {
    console.log(error.name + ' ' + error.message)
})

Both the example looks the same except some syntax. But writing code is cleaner with Promises than with callbacks because if you start using nesting callbacks we might get in trouble as the code just keeps getting indented and indented.

But in Promises, You can create “.then” multiple times,

watchSuitsPromise().then(message => {
    console.log(message)
  }).then(message => {
    console.log(message)
  }).then(message => {
    console.log(message)
  }).catch(error => {
    console.log(error.name + ' ' + error.message)
  })

which is better than using multiple callbacks i.e callbacks inside of another and another or nesting callback also called callback hell. So, Promises are great and solve the inside looping problem with callbacks.

Async/Await:

One of the hardest things about writing good JavaScript is dealing with heavily nested asynchronous code. Promises were created to solve the problem with callback hell, but there are still plenty of nested problems related to promises. This is where async/await comes in. JavaScript added async/await to allows developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write.

let’s look at the following Example with Promises and compare using Async/Await,

function makeRequest(location){
    return new Promise((resolve,reject)=>{
        console.log(`making request to ${location}`)
  if(location == 'google'){
      resolve('google says hello')
     }
   else{
        reject('we can only talk to google')
    }
 })
}
function processRequest(response){
    return new Promise((resolve,reject)=>{
        console.log('Processing response')
        resolve(`Extra Info  ${response}`)
    })
}
makeRequest('google').then(response=>{
        console.log('Response received')
        return processRequest(response)
}).then(processResponse=>{
console.log(processResponse)
    
})
.catch(err=>{
    console.log(err)
})

The above code is similar to the codes which are shown earlier. Two functions, One for sending a request and another for the response to that request.

Now we will see the same code with Async/Await and see some differences,

function makeRequest(location){
    return new Promise((resolve,reject)=>{
        console.log(`making request to ${location}`)
  if(location == 'google'){
    resolve('google says hello')
    }
  else{
        reject('we can only talk to google')
    }
})
}

function processRequest(response){
    return new Promise((resolve,reject)=>{
        console.log('Processing response')
        resolve(`Extra Info  ${response}`)
    })
}
async function doWork(){
    try{

        const response = await makeRequest('google')
        console.log('Response received')
        const processResponse = await processRequest(response)
        console.log(processResponse)
    }
catch(err){
    console.log(err)
}
}
doWork()
	

Here, we see a lot of differences in the code which also looks cleaner than code written with only ‘Promise’. We must wrap our code inside a function with an ‘async’ keyword before the function definition. Inside that function, code will be written in the try-catch block. ‘Try’ will take the code which might throw an error and ‘catch’ will send an error message if any error is caught. We must use await keyword before the functions that are going to be asynchronous. Otherwise, it will just return the promise but not the result of that promise being executed. Other than that Async/Await is pretty much similar to Promises. It makes easier for us to write promises and work with promises in our code.

You can further refer to the below links to learn more about Promises, Callbacks, and Async/Await…

Tags: AsyncAwaitCallbacksJavaScript
Share123Tweet77ShareSend
Previous Post

Full Stack Web Developer: A Guide to Learn

Next Post

Searching Algorithms in JavaScript

The Blogue Team

The Blogue Team

We are a team of passionate bloggers

Related Posts

How LinkedIn Powers Professional Networking: A Look Inside Its System Design
How To?

How LinkedIn Powers Professional Networking: A Look Inside Its System Design

by The Blogue Team
December 18, 2024
1.1k
A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs
Storage

A Deep Dive into Physical Storage Devices: From Floppy Disks to Modern SSDs

by The Blogue Team
December 17, 2024
1.1k
Facebook: The Engine Behind the World’s Largest Social Network
Facebook

Facebook: The Engine Behind the World’s Largest Social Network

by The Blogue Team
December 17, 2024
1.1k
Load More
Next Post
Searching Algorithms in JavaScript

Searching Algorithms in JavaScript

Where Writing Happens

  • Homepage
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2025 Blogue - Designed By Najus Digital.

Welcome Back!

Sign In with Google
OR

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Refresh
No Result
View All Result
  • Login

© 2025 Blogue - Designed By Najus Digital.

*By registering into our website, you agree to the Terms & Conditions. and Privacy Policy.
Enable Notifications OK No thanks