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?
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?
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.
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
});
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.
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.
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