What Is Promises

A promise is usually defined as a proxy for a worth which will eventually become
available. Promises are a method to affect asynchronous code, without writing too many callbacks in your code.

Async functions use the guarantees API as their building block, so understanding them is
fundamental albeit in newer code you will probably use async functions rather than promises.

How promises work

Once a promise has been called, it’ll start in pending state. This means that the caller
function continues the execution, while it waits for the promise to try to to its own processing, and give the caller function some feedback.

At now , the caller function waits for it to either return the promise during a resolved state, or in a rejected state, but as you recognize JavaScript is asynchronous, therefore the function continues its execution while the promise does it work.

Creating a promise

The Promise API exposes a Promise constructor, which you initialize using new Promise() :

let done = true
const isItDoneYet = new Promise((resolve, reject) => {
if (done) {
const workDone = 'Here is the thing I built'
resolve(workDone)
} else {
const why = 'Still working on something else'
reject(why)
}
})

As you can see the promise checks the done global constant, and if that’s true, we return a
resolved promise, otherwise a rejected promise.

Using resolve and reject we can communicate back a value, in the above case we just
return a string, but it could be an object as well.

Consuming a promise

how the promise can be consumed or used.

const isItDoneYet = new Promise()
//…
const checkIfItsDone = () => {
isItDoneYet
.then(ok => {
console.log(ok)
})
.catch(err => {
console.error(err)
})
}

Running checkIfItsDone() will execute the isItDoneYet() promise and will wait for it to
resolve, using the then callback, and if there is an error, it will handle it in the catch
callback.

Example of chaining promises

const status = response => {

if (response.status >= 200 && response.status < 300) { return Promise.resolve(response) } return Promise.reject(new Error(response.statusText)) } const json = response => response.json() fetch('/todos.json') .then(status) .then(json) .then(data => { console.log('Request succeeded with JSON response', data) }) .catch(error => { con

In this example, we call fetch() to get a list of TODO items from the todos.json file found in
the domain root, and we create a chain of promises.

Running fetch() returns a response, which has many properties, and within those we
reference:

  • status , a numeric value representing the HTTP status code
  • statusText , a status message, which is OK if the request succeeded

response also has a json() method, which returns a promise that will resolve with the
content of the body processed and transformed into JSON.

So given those premises, this is often what happens: the primary promise within the chain may be a function that we defined, called status() , that checks the response status and if it’s not a success response (between 200 and 299), it rejects the promise.

This operation will cause the promise chain to skip all the chained promises listed and can skip directly to the catch() statement at rock bottom , logging the Request failed text along side the error message.

If that succeeds instead, it calls the json() function we defined. Since the previous promise,
when successful, returned the response object, we catch on as an input to the second promise.

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: How to promises work In JavaScript

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password