Aren't promises just callbacks?

JavascriptCallbackPromiseQBluebird

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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 https://stackoverflow.com/q/22519784/1048572

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenjamin GruenbaumView Question on Stackoverflow
Solution 1 - JavascriptOscar PazView Answer on Stackoverflow
Solution 2 - JavascriptBergiView Answer on Stackoverflow
Solution 3 - JavascriptJohn WeiszView Answer on Stackoverflow
Solution 4 - JavascriptKarthickView Answer on Stackoverflow
Solution 5 - JavascriptDuncan LukkenaerView Answer on Stackoverflow
Solution 6 - JavascriptAyush JainView Answer on Stackoverflow
Solution 7 - JavascriptKjell SchubertView Answer on Stackoverflow
Solution 8 - JavascriptApoorvView Answer on Stackoverflow
Solution 9 - JavascriptHamid ShojaView Answer on Stackoverflow
Solution 10 - JavascriptWillem van der VeenView Answer on Stackoverflow