14

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?

3
  • 1
    We need it because in functional JS it is essential.
    – Redu
    Aug 17, 2016 at 19:16
  • 3
    There is nothing that can be done using Promises which cannot be done in "standard" JavaScript. It's a very powerful abstraction over async actions, resulting in cleaner code. Still, completely optional.
    – m90
    Aug 17, 2016 at 19:28
  • Also, if it's only one layer of nesting, I feel like it's easier to just use a callback.
    – D-Marc
    Sep 23, 2017 at 1:58

5 Answers 5

9

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.

1
  • Promises alone will not solve "call-back hell". They're also not the only way to solve such problems. Oct 26, 2022 at 9:38
4

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
});
1

Promise objects are used to perform asynchronous functions.

From the 1st line of the MDN docs:

The Promise object is used for asynchronous computations. A Promise represents a single asynchronous operation that hasn't completed yet, but is expected in the future.

1
  • The problem is the example in MDN and other places doesn't seem like it need to be written like that. If it just for writing cleaner code I can understand. Just not sure if there is something useful hidden behind.
    – Hp93
    Aug 18, 2016 at 3:00
0

It's just for write cleaner code. Look at this:

https://www.npmjs.com/package/q

It says:

On the first pass, promises can mitigate the “Pyramid of Doom”: the situation where code marches to the right faster than it marches forward.

-1

The Promise object is used for asynchronous computations. A Promise represents a single asynchronous operation that hasn't completed yet, but is expected in the future.

Here is an example. You can Run it here http://jsbin.com/yumapi/5/edit?html,js,output

function dieToss() {
  return Math.floor(Math.random() * 6) + 1;
}

console.log('1');
var promise = new RSVP.Promise(function(fulfill, reject) {
  var n = dieToss();
  if (n === 6) {
    fulfill(n);
  } else {
    reject(n);
  }
  console.log('2');
});

promise.then(function(toss) {
  console.log('Yay, threw a ' + toss + '.');  
}, function(toss) {
  console.log('Oh, noes, threw a ' + toss + '.');  
});

console.log('3');

This example Illustrates two things:

First, that the handlers we attached to the promise were indeed called after all other code ran, asynchronously.

Second, that the fulfillment handler was called only when the promise was fulfilled, with the value it was resolved with (in our case, the result of the dice toss). The same holds true for the rejection handler.

Credits to Mozilla and Toptotal

3
  • 1
    Hi, I understand how the syntax work. Just the example is not illustrate a good case to use the tool. Like in your example, we can replace fulfill() and reject() by the two console.log lines and achieve the same result.
    – Hp93
    Aug 18, 2016 at 3:24
  • 2
    You don't need it. Its just something that was made for cases like this and for Async requests. Its fine if you use your current method, as long as you can understand other peoples code when they use promises. Aug 19, 2016 at 18:42
  • Let me know if that helped! Aug 19, 2016 at 18:42

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.