5 Minutes of Javascript - ES6 Promises

5 Minutes of Javascript - ES6 Promises


This article is part of a series of articles about JavaScript features - The purpose of the series is to briefly explain (up to 5 minutes reading) a certain feature/library/concept or anything else related to Javascript so that you get excited and go explore about it.

Javascript is a single thread language (each tab in the browser has a single thread). That means that in order to create an asynchronous task in JavaScript we need to create a task and send it to the asynchronous tasks queued that is handled by the main thread.

The main thread handles the queue by executing the tasks one by one. The queue usually contains event handlers or callbacks that needs to be called once an async task is done.

So the flow basically is this: create an async task and send it an event handler/callback -> the async task runs by the main thread when possible -> when the async task ends the event handler/callback is added to the queue and executed once the main thread is available.

It's worth mention that in HTML5 web workers were introduced to address the issue of creating threads in the web. You can read more about it here.

ES5 async code example

Let's say we want to make a GET request to "https://reactjs.org" and if it is successful print to log "success!".

Let's use the XMLHttpRequest (XHR) object.

var request = new XMLHttpRequest();
var url = "https://reactjs.org/";

request.open("GET", url);
request.addEventListener("load", function(){
  if(request.status === 200)
  {
    console.log("success!");
  } else {
    consoe.log("error");
  }
}, false);


request.send();

With XHR we need to add an event listener with a handler function. This is similar to using callbacks. Here is an example of using callbacks with JQuery ajax.

$.ajax({url: "https://reactjs.org", 
    success: function(result, status, responseObject){
    console.log("success!");
}, error: function(xhr,status,error){
    consoe.log("error");
}});

Callback hell

One of the problems with callbacks is that the code is hard to debug and hard to read. We can easily reach what is called a "callback hell" just by running an async task inside a callback of an async task.

For example let's say we want to request data from a server (async task) and then write it into a file (async task) and then send the server an indication the the operation was successful (async task).

In ES5 it's not a very nice code! here are some examples.

ES6 Promises!

So a promise is really an object that implements the "Promise" API. But before getting into details lets see some basic example.

Let's implement the first example using the JavaScript Fetch API which uses promises.

fetch('https://reactjs.org')
  .then(function(response) {
    if(response.status === 200) {
      console.log("success!");
    }
  })

The fetch API really implements an http request task using a promise object. Once the request is done, the Promise object uses the resolve function to indicate that the promise was fulfilled and the result (response) is passed to the then function of the promise instance.

Avoiding callback hell!

With promises we can concat callbacks using the then function.

fetch('request url').then((response) => {
  return response.data
}).then((data) => {
  // Write the data to file
  // Return success/failure indication
}).then((result) => {
  // Send the indication to the server
}).

This is much more readable, maintainable and easier to debug.

The Promise Constructor

We can implement a promise on our own (in addition to using an API that implements the Promise API like the fetch function), using the Promise constructor and Promise API.

The Promise constructor receives a function that gets the resolve and reject methods (from the Promise API) as parameters. The function's purpose is to execute the async task. Therefore this function is called the "executer". In case the async task succeeds, the function should invoke the resolve method with a return value and in case it fails it should use the reject method with a failure value.

So for example, we can implement the fetch function using the XHR object we used before.

const fetch = (url) => new Promise(function(resolve, reject){

  const request = new XMLHttpRequest();

  request.open("GET", url);

  request.addEventListener("load", function(){
    if(request.status === 200)
    {
      resolve("success!");
    }
    else
    {
      reject("error!");
    }
  }, false);

  request.send();

});
 
  

And now we can use it just like we did earlier, even better!

fetch('https://reactjs.org')
  .then((data) => {
    console.log("success!");
  })
 
  

We can use the catch method to catch the error (that caused by reject)

fetch('https://reactjs.org')
  .then((data) => {
    console.log(data); // Prints "success!"
  }).catch(error => {
    console.log(error); // Prints "error!"
});
 
  

Promise.all and Promise.race

Two more cool features of the Promise API is Promise.all and Promise.any

Promise.all gets a Promises objects array and returns a Promise object that resolves once all of the promises are resolved. This is great if we want to do a task (let's say a UI task) after we have some conditions met (for example fetching data from multiple backend end-points).

Promise.race also receives an array of promises objects and returns a Promise object that resolves (or rejects) when the first promise gets resolved or rejected.


The Promise API has a more to offer including Promise states (Fulfilled, Rejected, Pending, Settled), The finally method and more. You can read and expend your knowledge in the MDN docs to get to know the API, and to get more in depth of how to use promises.

As Promises sometimes are hard to grasp at first, I think we focused on the basics which are important and sufficient for the understanding of how JavaScript Promises works.

It's worth to note that other programming language (like C++) have Promises API as well. All of the new JavaScript API's like fetch, and web cryptography implemented using Promises.


Thats it about Promises! A really great feature!

Till next time. Keep learning, keep exploring.

Some examples were taken from MDN and from the book "Learning ECMAScript 6" by Narayan Prusty which I highly recommend!


要查看或添加评论,请登录

Nir Parisian的更多文章

  • ???? ??????, ????????? ?? ???? ??????

    ???? ??????, ????????? ?? ???? ??????

    ??????? ????? ???? ????? ???? ???? ??????? ????? ????? ????? ?? ?-UI ???? ????? ?????. ?? ????? ??? ???? ?? "????? ????…

    1 条评论
  • ??? ??? ?VeeCon?

    ??? ??? ?VeeCon?

    ????? ????? ???? VeeCon ?????? ?????. ??? ??? ???? VeeCon ??? ??? Web3 ?????? ?? ??? ?????? ?? ?NFT ?? VeeFriends - ???…

    3 条评论
  • ?? ?? Oracle?

    ?? ?? Oracle?

    ?? ??? ???? ?????? ?????, ??? ???? ????? ?? ???? ?- web ??? ?????? ?????? ??????? ????? ?? ???????? ??????, ?? ??? ??…

  • ?? ?? DeFi

    ?? ?? DeFi

    ???? ???????? ??? ????? ???? ??? ???? ????. ???? ??????? ?? ??? ????? ??? ?? ???? - ?????, ????? ???????, ???? ???…

    2 条评论
  • ?????? ???????? ?-Web 3.0

    ?????? ???????? ?-Web 3.0

    ??????? ???? ?????????? Web 3.0 ??? ????? ?????? ?????? ?? ????? ???? ?????? ??? ??? ????????? ??????, ???? ?????? ??…

  • ??? NFT ???? ?? ????? ?????

    ??? NFT ???? ?? ????? ?????

    ????? ??? ??? - NFT ?? ??????, NFT ??? ??? ????? ?? ????? ??? ??? ???? ????? ??????? ????/????? ????, NFT ??? ??? ???…

    3 条评论
  • ?? ?? ???? ????

    ?? ?? ???? ????

    ?????? ??????? ?? ?????'??? ????? ??????? ???? ?????? ?????????? ?? ????? ????? (Smart Contracts) ???? ????? ??? ??????…

    5 条评论
  • ?????????? ????? ???? ?-Web 3.0

    ?????????? ????? ???? ?-Web 3.0

    ??? ?????? ?????? ?????? ????????? ?????????? ?? ???? ???? ??? ?????? ???? ???? ?? ????? ??????? ?? ??? ?????? ????????…

  • ??????? ?????? ???????? ?-Web 3.0

    ??????? ?????? ???????? ?-Web 3.0

    ?????? ?? ?? ???? ????? ???? ?????? ????? ?????? ?????????, ????? ?? ?????, ????? ????? ??? ????? ?????? ?????? ??…

  • ?? ?? DAO?

    ?? ?? DAO?

    ??? ????? ?? DAO ????? ?????? ?? ??? ?????? ????? ???????? ?Web 3.0, ?? ????? ??????????, ?? ????? ?????? ???????…

    2 条评论

社区洞察

其他会员也浏览了