PROMISE in JAVASCRIPT

Beribey
4 min readFeb 11, 2021

The promise is used quite a lot in both front-end (AngularJS) and back-end (NodeJS), so mastering this concept will help you a lot in coding and interviews.

Photo by Max Chen on Unsplash

Asynchronous programming in Javascript

Anyone who has ever done AJAX knows that Javascript ; the asynchronously connects to the server functions behind do not wait for the AJAX function to finish but continue to run.

var xxxImage = ajax.get("hotgirl.info");
console.log(xxxImage);

Therefore, to get the result of the ajax function, we must pass it a callback. After the AJAX function gets the result, it will call the callback function with the result obtained.

// Pass callback to function ajax
var callback = function (image) {
console.log (image);
};
ajax.get("hotgirl.info", callback);

// Can be abbreviated as follows
ajax.get("hotgirl.info", function (image) {
console.log (image);
})

What’s wrong with this approach? Using overlapping callbacks makes the code confusing and difficult to read; Catching exceptions and displaying errors also become complicated.

var car = buycar();
var girl = goout(car);
var abcd = goToHotel(y);

// That must use callback heap, creating callback hell
buycar(function(car) {
goout(car, function(girl) {
goToHotel(hotel, function(z) {
// Do something, who knows
});
});
});

To solve this problem, developers invented a concept called promises.

What is a Promise?

Promises concept explained by MDN is quite ambiguous and somewhat … confusing:

The Promise object is used for asynchronous computations. A Promise An operation that hasnt completed yet, but is expected in the future.

Photo by Katrina Holmgren on Unsplash

A promise has the following 3 states:

  • pending
  • fulfilled
  • reject

In the past, for you to try to study, your parents said, “If you try to get into college, you will buy a BMW to go to school. Now, what you get is a promise, not a BMW.

When a promise is fulfilled, the promise will call the callback in the then function. Conversely, when the promise is broken, the promise calls the callback in the catch function.

Return to the example at the beginning of the article. At this point the ajax function will return a promise. This function promises to be “If you take XXX photos, I will give it to you”. Now the function’s result is a promise, not an XXX image.

function get (url) {
return new Promise ((resolve, reject) => {
// Get the picture from abc.com
// If there is an error, I can not promise
if (error) reject ("Error");

// If obtained, then fulfill the promise
resolve (xxxImage);
});
}

var promise = ajax.get ("hotgirl.info");
promise
.then (image => fap)
.catch ((error) => alert (error));

Why we should use PROMISE?

Promises are good at the following points:

  • Promise supports “chaining”
  • Promises make it easier to catch errors
  • Handling asynchronous

Let’s analyze the good points of Promise.

1. Promise chaining

The return value of the then function is another promise. So we can use promises to call asynchronous functions consecutively. The above function can be rewritten as follows:

// Dùng callback hell
buycar(function(car) {
goout(car, function(girl) {
goToHotel(hotel, function(z) {
// Do something, who knows
});
});
});

// Use promises, lightweight and easy to read code
buycar
.then(goout)
.then(goToHotel)
.then(function() { /*Do something, who knows*/ });

2. Promises make it easier to catch errors

In the above example, we call 3 functions in turn: buycar, goout, goToHotel.

As long as one of these 3 functions fails, the promise will pass the reject state. At this point the callback in the catch function will be called. Catching errors has become a lot easier

// When a function fails, the promise is rejected.
function send_hotel () {
return Promise ((response, reject) => {
reject ("Sorry today, I am red light");
});
}


please_mother_mua_xe
.then (played_player)
.then (hotel_to_hotel)
.then (function () {/ * Do something, who knows * /})
.catch (function (err) {
console.log (err); // "Sorry today I light red"
console.log ("bad luck");
});

3. Asynchronous handling

Let’s say you want 3 different AJAX functions. You need the results returned for these 3 functions before you can continue running. With the callback, this will be quite difficult to do. However, promises support the Promise.all function, allowing the results of multiple promises together.

Conclusion

With its advantages, promises are gradually replacing callbacks. Of course not completely replaced. For simple functions, using callbacks is shorter and easier to understand than promises.

Promises are used a lot in AngularJS and some NodeJS modules. Mastering the Promise concept will help you to code a lot less.

--

--

Beribey

Always be nice to anybody who has access to my toothbrush.