507

I've been developing JavaScript for a few years and I don't understand the fuss about promises at all.

It seems like all I do is change:

api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
        });
    });
});

Which I could use a library like async for anyway, with something like:

api().then(function(result){
     api2().then(function(result2){
          api3().then(function(result3){
               // do work
          });
     });
});

Which is more code and less readable. I didn't gain anything here, it's not suddenly magically 'flat' either. Not to mention having to convert things to promises.

So, what's the big fuss about promises here?

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 12
    **On-topic**: there is a really informative article about Promises on Html5Rocks: http://www.html5rocks.com/en/tutorials/es6/promises/ – ComFreek Mar 20 '14 at 17:45
  • 2
    Fyi the answer you accepted is the same old list of the trivial benefits that are not the point of promises at all and didn't even convince me to use promises :/. What convinced me to use promises was the DSL aspect as described in Oscar's answer – Esailija Mar 31 '14 at 13:07
  • @Esailija fine, your leet speak convinced me. I've accepted the other answer although I think Bergi's one raises some really good (and different) points too. – Benjamin Gruenbaum Apr 08 '14 at 18:27
  • 1
    @Esailija "What convinced me to use promises was the DSL aspect as described in Oscar's answer" << What is "DSL"? and what's the "DSL aspect" that you're referring to? – monsto Mar 03 '18 at 05:09
  • 3
    @monsto: DSL: Domain Specific Language, a language purposely designed to be used in a particular subset of a system (e.g. SQL or ORM to talk to the database, regex to find patterns, etc). In this context the "DSL" is the Promise's API which, if you structure your code the way Oscar did, is almost like syntactic sugar that supplements JavaScript to address the particular context of async operations. Promises create some idioms that turn them into almost a language designed to allow the programmer to more easily grasp the somewhat elusive mental flow of this type of structures. – Michael Ekoka Apr 11 '18 at 07:14

11 Answers11

709

Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});

Certainly, not much less code, but much more readable.

But this is not the end. Let's discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});

Pretty much the same as a try { ... } catch block.

Even better:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
}).then(function() {
     //do something whether there was an error or not
     //like hiding an spinner if you were performing an AJAX request.
});

And even better: What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:

Promise.all([api(), api2(), api3()]).then(function(result) {
    //do work. result is an array contains the values of the three fulfilled promises.
}).catch(function(error) {
    //handle the error. At least one of the promises rejected.
});

Hope you see Promises in a new light now.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
  • 145
    They really shouldn't have named it as "Promise". "Future" is at least 100x better. – Pacerier May 02 '14 at 18:47
  • 14
    @Pacerier because Future wasn't tainted by jQuery? – Esailija Jan 31 '15 at 12:01
  • 12
    Alternate pattern (depending on what is desired: api().then(api2).then(api3).then(doWork); That is, if api2/api3 functions take input from the last step, and return new promises themselves, they can just be chained without extra wrapping. That is, they compose. – Dtipson Dec 22 '15 at 19:11
  • 1
    What if there is async operatings in `api2` and `api3`? would the last `.then` only be called once those async operations are completed? – NiCk Newman Jan 24 '16 at 19:45
  • I have an issue with the definition: 'future result of an asynchronous operation'. Isn't a callback exactly that? – Jin Nov 10 '17 at 22:40
  • Another advantage of Promises is the ability to assign a variable with a Promise value. This opens up the possibility of separating business logic that doesn't belong together but which has a shared dependency of that particular call, etc. – thisguyheisaguy Feb 01 '18 at 16:05
  • "... true benefits: ... check for any error in any of the steps?" -- this can actually be equally achieved with callbacks: https://github.com/dmitriz/cpsfy – Dmitri Zaitsev Jun 09 '19 at 03:27
  • 1
    One more thing is that promises get higher priority event queue https://stackoverflow.com/questions/19743354/does-javascript-event-queue-have-priority – SPS Dec 20 '19 at 08:06
  • 2
    I found this answer to be one of the best exemples on how to use promises. So, I don't understand the heavy downvoting? (-6 as of today) – Déjà vu Mar 27 '20 at 08:26
197

Yes, Promises are asynchronous callbacks. They can't do anything that callbacks can't do, and you face the same problems with asynchrony as with plain callbacks.

However, Promises are more than just callbacks. They are a very mighty abstraction, allow cleaner and better, functional code with less error-prone boilerplate.

So what's the main idea?

Promises are objects representing the result of a single (asynchronous) computation. They resolve to that result only once. There's a few things what this means:

Promises implement an observer pattern:

  • You don't need to know the callbacks that will use the value before the task completes.
  • Instead of expecting callbacks as arguments to your functions, you can easily return a Promise object
  • The promise will store the value, and you can transparently add a callback whenever you want. It will be called when the result is available. "Transparency" implies that when you have a promise and add a callback to it, it doesn't make a difference to your code whether the result has arrived yet - the API and contracts are the same, simplifying caching/memoisation a lot.
  • You can add multiple callbacks easily

Promises are chainable (monadic, if you want):

  • If you need to transform the value that a promise represents, you map a transform function over the promise and get back a new promise that represents the transformed result. You cannot synchronously get the value to use it somehow, but you can easily lift the transformation in the promise context. No boilerplate callbacks.
  • If you want to chain two asynchronous tasks, you can use the .then() method. It will take a callback to be called with the first result, and returns a promise for the result of the promise that the callback returns.

Sounds complicated? Time for a code example.

var p1 = api1(); // returning a promise
var p3 = p1.then(function(api1Result) {
    var p2 = api2(); // returning a promise
    return p2; // The result of p2 …
}); // … becomes the result of p3

// So it does not make a difference whether you write
api1().then(function(api1Result) {
    return api2().then(console.log)
})
// or the flattened version
api1().then(function(api1Result) {
    return api2();
}).then(console.log)

Flattening does not come magically, but you can easily do it. For your heavily nested example, the (near) equivalent would be

api1().then(api2).then(api3).then(/* do-work-callback */);

If seeing the code of these methods helps understanding, here's a most basic promise lib in a few lines.

What's the big fuss about promises?

The Promise abstraction allows much better composability of functions. For example, next to then for chaining, the all function creates a promise for the combined result of multiple parallel-waiting promises.

Last but not least Promises come with integrated error handling. The result of the computation might be that either the promise is fulfilled with a value, or it is rejected with a reason. All the composition functions handle this automatically and propagate errors in promise chains, so that you don't need to care about it explicitly everywhere - in contrast to a plain-callback implementation. In the end, you can add a dedicated error callback for all occurred exceptions.

Not to mention having to convert things to promises.

That's quite trivial actually with good promise libraries, see How do I convert an existing callback API to promises?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    hi Bergi, would you have anything interesting to add to this SO question? http://stackoverflow.com/questions/22724883/js-deferred-promise-future-compared-to-functional-languages-like-scala – Sebastien Lorber Apr 01 '14 at 14:38
  • 1
    @Sebastien: I don't know much about Scala (yet), and I could only repeat what Benjamin said :-) – Bergi Apr 01 '14 at 14:57
  • Sorry, this is a pretty good answer, but Petka (@Esailija) convinced me that the other one makes a better case for people having this specific issue. – Benjamin Gruenbaum Apr 08 '14 at 18:23
  • 4
    Just a little remark: you cannot use `.then(console.log)`, as console.log depends on the console context. This way it will cause an illegal invocation error. Use `console.log.bind(console)` or `x => console.log(x)` to bind context. – Tamas Hegedus Nov 20 '15 at 11:07
  • 3
    @hege_hegedus: There are environments where `console` methods are already bound. And of course, I only said that both nestings have exactly the same behaviour, not that any of them would work :-P – Bergi Nov 20 '15 at 11:46
  • 1
    That was great. This is what I needed: less code and more interpretation. Thank you. – Adam Patterson Mar 05 '17 at 20:58
  • "They can't do anything that callbacks can't do", is this well written? – Tiago Martins Peres Sep 18 '20 at 10:21
  • 1
    @Tiago What would you have written instead? "*Callbacks can do everything that promises can do*"? – Bergi Sep 18 '20 at 19:09
  • @Bergi much more clear yes. Can add "and more" in the end too – Tiago Martins Peres Sep 18 '20 at 20:00
  • hi @Bergi excellent answer +1, does this mean that the **`return` of the callbacks** of a `then()` (the success callback and the failure callback) at the end of the day is (becomes) the `return` of the `then()` *method itself*? –  Feb 12 '23 at 03:05
  • Similarly, are the `return` of the callbacks of a `finally()`and a `catch()` the `return` of *those methods themselves*? @Bergi , thanks in advance –  Feb 12 '23 at 03:07
  • 1
    @GeorgeMeijer No, that is impossible! The `.then()` method returns immediately, before the handler callback is even called. It returns a *new* (different) promise, that is resolved to the result of the respective handler. – Bergi Feb 12 '23 at 05:02
  • Thank you very much @Bergi +1. The `catch()` and `finally()` methods internally call `.then()`, right?, therefore the same applies, right? –  Feb 12 '23 at 17:58
  • 1
    @GeorgeMeijer Yes indeed – Bergi Feb 12 '23 at 18:00
27

In addition to the already established answers, with ES6 arrow functions Promises turn from a modestly shining small blue dwarf straight into a red giant. That is about to collapse into a supernova:

api().then(result => api2()).then(result2 => api3()).then(result3 => console.log(result3))

As oligofren pointed out, without arguments between api calls you don't need the anonymous wrapper functions at all:

api().then(api2).then(api3).then(r3 => console.log(r3))

And finally, if you want to reach a supermassive black hole level, Promises can be awaited:

async function callApis() {
    let api1Result = await api();
    let api2Result = await api2(api1Result);
    let api3Result = await api3(api2Result);

    return api3Result;
}
John Weisz
  • 30,137
  • 13
  • 89
  • 132
  • 8
    That makes Promises sound like a cosmic catastrophe, which I don't think was your intention. – Michael McGinnis Oct 31 '17 at 08:13
  • 1
    If you are not using the arguments in the `apiX` methods, you might as well skip the arrow functions altogether: `api().then(api2).then(api3).then(r3 => console.log(r3))`. – oligofren Nov 07 '17 at 18:55
  • @MichaelMcGinnis -- The beneficial impact of Promises on a dull callback hell is like an exploding supernova in a dark corner of space. – John Weisz May 24 '18 at 08:19
  • I know you mean it poetically, but promises are quite far from "supernova". [Breaking monadic law](https://stackoverflow.com/a/50173415/1614973) or lacking support for more poweful use cases such as cancellation or returning multiple values come to mind. – Dmitri Zaitsev Jun 09 '19 at 04:26
24

In addition to the awesome answers above, 2 more points may be added:

1. Semantic difference:

Promises may be already resolved upon creation. This means they guarantee conditions rather than events. If they are resolved already, the resolved function passed to it is still called.

Conversely, callbacks handle events. So, if the event you are interested in has happened before the callback has been registered, the callback is not called.

2. Inversion of control

Callbacks involve inversion of control. When you register a callback function with any API, the Javascript runtime stores the callback function and calls it from the event loop once it is ready to be run.

Refer The Javascript Event loop for an explanation.

With Promises, control resides with the calling program. The .then() method may be called at any time if we store the promise object.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Karthick
  • 2,031
  • 1
  • 13
  • 18
  • 1
    I don't know why but this seems like a better answer. – radiantshaw Feb 26 '19 at 05:40
  • Nice, this ->"With Promises, control resides with the calling program. The .then() method may be called at any time if we store the promise object." – HopeKing Apr 10 '21 at 09:41
  • This should be the correct answer especially the semantic difference part. It was in my mind for a while but couldn't put it to words but this is the core difference between promises and callbacks – Ramy Farid Sep 19 '22 at 16:47
15

In addition to the other answers, the ES2015 syntax blends seamlessly with promises, reducing even more boilerplate code:

// Sequentially:
api1()
  .then(r1 => api2(r1))
  .then(r2 => api3(r2))
  .then(r3 => {
      // Done
  });

// Parallel:
Promise.all([
    api1(),
    api2(),
    api3()
]).then(([r1, r2, r3]) => {
    // Done
});
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
5

Promises are not callbacks, both are programming idioms that facilitate async programming. Using an async/await-style of programming using coroutines or generators that return promises could be considered a 3rd such idiom. A comparison of these idioms across different programming languages (including Javascript) is here: https://github.com/KjellSchubert/promise-future-task

Kjell Schubert
  • 147
  • 1
  • 2
5

No, Not at all.

Callbacks are simply Functions In JavaScript which are to be called and then executed after the execution of another function has finished. So how it happens?

Actually, In JavaScript, functions are itself considered as objects and hence as all other objects, even functions can be sent as arguments to other functions. The most common and generic use case one can think of is setTimeout() function in JavaScript.

Promises are nothing but a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks.

The Promise receives two Callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.

Ayush Jain
  • 337
  • 3
  • 10
3

No promises are just wrapper on callbacks

example You can use javascript native promises with node js

my cloud 9 code link : https://ide.c9.io/adx2803/native-promises-in-node

/**
* Created by dixit-lab on 20/6/16.
*/

var express = require('express');
var request = require('request');   //Simplified HTTP request client.


var app = express();

function promisify(url) {
    return new Promise(function (resolve, reject) {
    request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        resolve(body);
    }
    else {
        reject(error);
    }
    })
    });
}

//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
//get the post with post id 100
promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
var obj = JSON.parse(result);
return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
})
.catch(function (e) {
    console.log(e);
})
.then(function (result) {
    res.end(result);
}
)

})


var server = app.listen(8081, function () {

var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)

})


//run webservice on browser : http://localhost:8081/listAlbums
Apoorv
  • 222
  • 2
  • 9
2

Promises overview:

In JS we can wrap asynchronous operations (e.g database calls, AJAX calls) in promises. Usually we want to run some additional logic on the retrieved data. JS promises have handler functions which process the result of the asynchronous operations. The handler functions can even have other asynchronous operations within them which could rely on the value of the previous asynchronous operations.

A promise always has of the 3 following states:

  1. pending: starting state of every promise, neither fulfilled nor rejected.
  2. fulfilled: The operation completed successfully.
  3. rejected: The operation failed.

A pending promise can be resolved/fullfilled or rejected with a value. Then the following handler methods which take callbacks as arguments are called:

  1. Promise.prototype.then() : When the promise is resolved the callback argument of this function will be called.
  2. Promise.prototype.catch() : When the promise is rejected the callback argument of this function will be called.

Although the above methods skill get callback arguments they are far superior than using only callbacks here is an example that will clarify a lot:

Example

function createProm(resolveVal, rejectVal) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.5) {
                console.log("Resolved");
                resolve(resolveVal);
            } else {
                console.log("Rejected");
                reject(rejectVal);
            }
        }, 1000);
    });
}

createProm(1, 2)
    .then((resVal) => {
        console.log(resVal);
        return resVal + 1;
    })
    .then((resVal) => {
        console.log(resVal);
        return resVal + 2;
    })
    .catch((rejectVal) => {
        console.log(rejectVal);
        return rejectVal + 1;
    })
    .then((resVal) => {
        console.log(resVal);
    })
    .finally(() => {
        console.log("Promise done");
    });
  • The createProm function creates a promises which is resolved or rejected based on a random Nr after 1 second
  • If the promise is resolved the first then method is called and the resolved value is passed in as an argument of the callback
  • If the promise is rejected the first catch method is called and the rejected value is passed in as an argument
  • The catch and then methods return promises that's why we can chain them. They wrap any returned value in Promise.resolve and any thrown value (using the throw keyword) in Promise.reject. So any value returned is transformed into a promise and on this promise we can again call a handler function.
  • Promise chains give us more fine tuned control and better overview than nested callbacks. For example the catch method handles all the errors which have occurred before the catch handler.
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
2

Promises allows programmers to write simpler and far more readable code than by using callbacks.


In a program, there are steps we want to do in series.

function f() {
   step_a();
   step_b();
   step_c();
   ...
}

There's usually information carried between each step.

function f( x ) {
   const a = step_a( x );
   const b = step_b( a );
   const c = step_c( b );
   ...
}

Some of these steps can take a (relatively) long time, so sometimes you want to do them in parallel with other things. One way to do that is using threads. Another is asynchronous programming. (Both approaches has pros and cons, which won't be discussed here.) Here, we're talking about asynchronous programming.

The simple way to achieve the above when using asynchronous programming would be to provide a callback which is called once a step is complete.

// Each of step_* calls the provided function with its return value once complete.
function f() {
   step_a( x,
      function( a ) {
         step_b( a,
            function( b ) {
               step_c( b,
                  ...
               );
            },
         );
      },
   );
}

That's quite hard to read. Promises offer a way to flatten the code.

// Each of step_* returns a promise.
function f( x ) {
   step_a( x )
   .then( step_b )
   .then( step_c )
   ...
}

The object returned is called a promise because it represents the future result (i.e. promised result) of the function (which could be a value or an exception).

As much as promises help, it's still a bit complicated to use promises. This is where async and await come in. In a function declared as async, await can be used in lieu of then.

// Each of step_* returns a promise.
async function f( x )
   const a = await step_a( x );
   const b = await step_b( a );
   const c = await step_c( b );
   ...
}

This is undeniably much much more readable than using callbacks.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

JavaScript Promises actually use callback functions to determine what to do after a Promise has been resolved or rejected, therefore both are not fundamentally different. The main idea behind Promises is to take callbacks - especially nested callbacks where you want to perform a sort of actions, but it would be more readable.

Hamid Shoja
  • 3,838
  • 4
  • 30
  • 45