Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Promise in JS

Tags:

javascript

I've just read about Promise on both MDN. I can understand the syntax but not sure about why we need it.

Is there a specific case that can only be done by using Promise? Or is it just a way to write cleaner code?

like image 336
Hp93 Avatar asked Aug 17 '16 19:08

Hp93


2 Answers

Currently, there's nothing that can be done with JavaScript promises that could not be done without them, as the original Promise implementation was also JavaScript code. One of the arguments for using promises is getting rid of the so-called "callback hell", which looks something like this:

setTimeout(function () {
    setTimeout(function() {
        setTimeout(function() {
            // do something
        }); 
    }); 
});

Which can be easily solved by simple giving names to the functions:

setTimeout(doSomething);

function doSomething() {
    setTimeout(doSomethingElse);
}

function doSomethingElse() {
    // do something
}

So "callback hell" is a misconception, the real problem should be called "anonymous-function hell". And by the way, simply using promises alone will also not prevent that, like in the following sample:

samplePromise().then(function () {
    samplePromise().then(function () {
        samplePromise().then( function () {
            // do something
        });
    });
});

See a pattern, here? We have once more anonymous functions as the culprit for deep nesting.

That being said, there's one use case that might arguably benefit from a promise, and that is when exceptions from more than one asynchronous call could be caught by the same catch block:

new Promise(function (resolve, reject) {
    resolve("Blah");
}).then(function () {
    // do something
}).then(function () {
    // do something
}).catch(function (reason) {
    // error handling
});
like image 194
Diogo Eichert Avatar answered Oct 10 '22 01:10

Diogo Eichert


Promises give us the ability to write cleaner code but reducing (or entirely removing) call-back hell.

In addition, callbacks are the backbone of some new syntax features coming in ES2017, such as async functions, which allows an even cleaner way of writing code.

The third thing that promises do is not immediately apparent when you first learn the syntax -- automatic error handling. Promises allow errors to be passed down the chain and handled in one common place without having to put in layers of manual error handling.

like image 40
Jeremy J Starcher Avatar answered Oct 10 '22 00:10

Jeremy J Starcher