PROMISE in JAVASCRIPT

Photo by Max Chen on Unsplash

Asynchronous programming in Javascript

var xxxImage = ajax.get("hotgirl.info");
console.log(xxxImage);
// 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);
})
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
});
});
});

What is a Promise?

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
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?

// 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*/ });
// 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");
});

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store