From what I have understood there are three ways of calling asynchronous code:
Events, e.g. request.on("event", callback);
Callbacks, e.g. fs.open(path, flags, mode, callback);
Promises
I found the node-promise library but I don’t get it.
Could someone explain what promises are all about and why I should use it?
Also, why was it removed from Node.js?
Since this question still has many views (like mine) I wanted to point out that:
node-promise looks rather dead to me (last commit was about 1 year ago) and contains nearly no tests.
The futures module looks very bloated to me and is badly documented (and I think that the naming conventions are just bad)
The best way to go seems to be the q framework, which is both active and well-documented.
Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.
The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).
By removing them from the core node.js, it created possibility of building up modules with different implementations of promises that can sit on top of the core. Some of these are node-promise and futures.
A promise is a "thing" which represents the "eventual" results of an operation so to speak. The point to note here is that, it abstracts away the details of when something happens and allows you to focus on what should happen after that something happens. This will result in clean, maintainable code where instead of having a callback inside a callback inside a callback, your code will look somewhat like:
var request = new Promise(function(resolve, reject) {
//do an ajax call here. or a database request or whatever.
//depending on its results, either call resolve(value) or reject(error)
//where value is the thing which the operation's successful execution returns and
//error is the thing which the operation's failure returns.
});
request.then(function successHandler(result) {
//do something with the result
}, function failureHandler(error) {
//handle
});
The promises' spec states that a promise's
then
method should return a new promise that is fulfilled when the given successHandler or the failureHandler callback is finished. This means that you can chain together promises when you have a set of asynchronous tasks that need to be performed and be assured that the sequencing of operations is guaranteed just as if you had used callbacks. So instead of passing a callback inside a callback inside a callback, the code with chained promises looks like:
var doStuff = firstAsyncFunction(url) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
success: function(data) {
resolve(data);
},
error: function(err) {
reject(err);
}
});
};
doStuff
.then(secondAsyncFunction) //returns a promise
.then(thirdAsyncFunction); //returns a promise
To know more about promises and why they are super cool, checkout Domenic's blog : http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
This new tutorial on Promises from the author of PouchDB is probably the best I've seen anywhere. It wisely covers the classic rookie mistakes showing you correct usage patterns and even a few anti-patterns that are still commonly used - even in other tutorials!!
http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
Enjoy!
PS I didn't answer some other parts of this question as they've been well covered by others.
Mike Taulty has a series of videos, each of them less than ten minutes long, describing how the WinJS Promise library works.
These videos are quite informative, and Mike manages to show the power of the Promise API with a few well-chosen code examples.
var twitterUrl = "http://search.twitter.com/search.json?q=windows";
var promise = WinJS.xhr({ url: twitterUrl });
promise = promise.then(
function (xhr) {
},
function (xhr) {
// handle error
});
The treatment of how exceptions are dealt with is particularly good.
In spite of the WinJs references, this is a general interest video series, because the Promise API is broadly similar across its many implementations.
RSVP is a lightweight Promise implementation that passes the Promise/A+ test suite. I quite like the API, because it is similar in style to the WinJS interface.
Update Apr-2014
Incidentally, the WinJS library is now open source.
Another advantage of promises is that error handling and exception throwing and catching is much better than trying to handle that with callbacks.
The bluebird library implements promises and gives you great long stack traces, is very fast, and warns about uncaught errors. It also is faster and uses less memory than the other promise libraries, according to http://bluebirdjs.com/docs/benchmarks.html
What exactly is a Promise ?
A promise is simply an object which represents the result of an async operation. A promise can be in any of the following 3 states :
pending :: This is the initial state, means the promise is neither fulfilled nor rejected.
fulfilled :: This means the promise has been fulfilled, means the value represented by promise is ready to be used.
rejected :: This means the operations failed and hence can't fulfill the promise.
Apart from the states, there are three important entities associated to promises which we really need to understand
executor function :: executor function defines the async operation which needs to be performed and whose result is represented by the promise. It starts execution as soon as the promise object is initialized.
resolve :: resolve is a parameters passed to the executor function , and in case the executor runs successfully then this resolve is called passing the result.
reject :: reject is another parameter passed to the executor function , and it is used when the executor function fails. The failure reason can be passed to the reject.
So whenever we create a promise object, we've to provide Executor, Resolve and Reject.
Reference :: Promises
I've been also looking into promises in node.js recently. To date the when.js seems to be the way to go due to its speed and resource use, but the documentation on q.js gave me a lot better understanding. So use when.js but the q.js docs to understand the subject.
From the q.js readme on github:
If a function cannot return a value or throw an exception without
blocking, it can return a promise instead. A promise is an object that
represents the return value or the thrown exception that the function
may eventually provide. A promise can also be used as a proxy for a
remote object to overcome latency.
Promise object represents the completion or failure of an asynchronous operation.
So in order to implement a promise, you need two parts:-
1.Creating Promise:
The promise constructor accepts a function called an executor that has
2 parameters resolve and reject.
function example(){
return new Promise (function(resolve , reject){ //return promise object
if(success){
resolve('success'); //onFullfiled
}else{
reject('error'); //onRejected
}
})
}
2.Handling Promise:
Promise object has 3 methods to handle promise objects:-
1.Promise.prototype.catch(onRejected)
2.Promise.prototype.then(onFullfiled)
3.Promise.prototype.finally(onFullfiled,onRejected)
example.then((data) =>{
//handles resolved data
console.log(data); //prints success
}).catch((err) => {
//handles rejected error
console.log(err); //prints error
})
Related
I have a methodology question. Currently I am using $q.all to capture multiple promises in a single return, then processing all the results as single request.
ie: $q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...}
However, I am noticing that sometimes different promises are being returned at significantly different time frames. All the promises are http calls to third party sites. When any particular promise is delayed by say 8 seconds...or 14 seconds, then the final results of all promises are delayed by that same duration. The weakest...rather 'slowest'...link syndrome.
What is another method that I can use to call all the promises at the same time yet still allow for results to be processed, and viewed by the user, as they come in? To NOT wait on all of them to be returned before processing them all at once?
As suggested in the comments you could just use them separately, but if you really want to call them all at the same time and handle them in one promise, you can use the notify-callback of the promise. I've created an extension to $q that uses this notify() function to resolve the promises as one:
app.run(function($q){
$q.each = function(promises){
var deferred = $q.defer();
promises.forEach(function(promise){
promise.then(function(data){
deferred.notify(data);
});
});
return deferred.promise;
};
});
This is a pretty naive implementation that doesn't handle errors for instance, but it gives you an idea of what's involved.
Then you'd just use it like this:
var promises = [promise1(),promise2(),promise3(),promise(4),promise5()];
$q.each(promises).then(null, null, function(data){
console.log(data); // This is called when each promise resolves.
});
Here's a Plunker showing this in action
Keep in mind that the methods like then() or $q.all() do not determine how the promises execute; they merely establish the semantics for when you want to respond. What I mean is, the promises start running when you create them even though a fluent reading of myPromise.then(doSomething) might seem to imply otherwise.
Combine that with the fact that $q.all doesn't so much "combine promises" as it creates a new promise that resolves or rejects based on the resolution or rejection status of the original promises; and that a promise is not limited to only a single handler...
promise1.then(function () {
//stuff that only cares about promise1 and needn't wait for the others
});
$q.all(promise1, promise2, ...).then(function () {
//stuff that can't be done until everything finishes
});
According to MDN:
The executor function is executed immediately by the Promise implementation, passing resolve and reject functions
What were the actual reasons for this decision?
Why promises are not lazy?
What were the actual reasons for this decision?
The revealing Promise constructor with the callback was just an improvement over the older deferred pattern. The callback was never meant to provide choice over the evaluation time, it is supposed to provide a scope with error handling for the resolver functions.
Why promises are not lazy?
Because promises represent the asynchronous result values, nothing more. They're kept simple, without featuring lazyness (and representing the whole computation, with methods to start/repeat/etc). You can trivially get that by using a function that returns a promise instead.
Promises are meant to provide continuations, and actual state of standard Promise object proposes the following pattern:
function doStuff() {
return new Promise((resolve, reject) => { // execution function
// Do stuff here
});
}
I would ask a question myself to understand why Promise's execution function is called immediatelly: where you would do the promised stuff?
Clearly, it's called immediatelly because you're making a promise that some stuff will be successfully or unsucessfully done, and that stuff should start to be processed as soon as you call the enclosing function to avoid confusion to the caller.
The point of a promise is to have something to return from a function that callers can attach their callbacks to rather than pass them in. The constructor is a red herring to answer "why", as it exists solely to wrap old callback-style code in an imperfect world.
All JS functions are synchronous, even those returning a promise (es8's async is syntactic sugar).
The Promise constructor executor function exists to provide unified error handling. Consider:
function foo() {
""(); // throws TypeError
return Promise(resolve => {
""(); // rejects promise with TypeError
});
}
Callers would need both try{ foo().catch(failed); } catch(e) { failed(e); } = Sucks.
So put all your synchronous code inside the executor function to unify errors for your callers. That's what it's for, which I think is your real question.
"Lazy" execution would defeat the purpose of unifying error handling of all your code.
Although I am working with the HTTP promise object in AngularJS, I don't have a clear concept of what an HTTP promise object actually is and what the is difference between an HTTP promise object and a traditional object in AngularJS!
Would anybody explain this, please?
A Promise is a concept for asynchronous operations. Basically it represents an object that can be available at any point from now into the future.
It has three states:
Pending
Fulfilled (it completed successfully)
Rejected (it failed)
You handle the states of your Promise with two methods, then() and catch().
then() provides you with the expected object from your asynchronous call if successful, and catch() will allow you to handle the error.
A scenario where you might use a Promise is when you're making a network call, for example:
getData(): Promise<Array<string>> {
return this.http.get("http://a-test-api.com/api/getdata").toPromise();
}
You'd then use it like this:
this.getData().then(function (stringArray) {
self.data = stringArray;
});
You can find some more information on the concept here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promises are a concept. This is a question on AngularJS Promises, which are a bit different from other promises, but the concept across libraries are fundamentally the same.
What are Asynchronous Processes?
If you know what this is, skip it and read the next header, otherwise:
When you have code, it generally runs in sequential order like so:
object.method() // First,
variable = "something"; // Second,
for(var i=0; i<2; i++) {
resp = object.makeHttpRequest();
console.log(resp.data + " was #" + i);
} // Third,
console.log("Done"); // Last.
Each step is performed after the previous finishes. This can be a problem when that for loop takes a long time (imagine the HTTP request takes a long time). The request would hang an entire process until the HTTP request is finished. Very bad.
Node.js handles this by default using a callback pattern. When you call a function that is blocking (takes a long time, like reading a file on disk or making an HTTP request), you register a callback function it will call after finishing. It will apply the function with the data from the blocking function when it finishes. This allows you to run other code while that blocking function finishes.
As many Node.js developers will tell you, this code can get very messy, very fast. Instead, AngularJS (and other libraries) will return you a Promise for when the code will finish. It allows you to use a Promise Pattern.
I know what asynchronous stuff is
Promises are conceptually similar to callbacks, but much cleaner and allow a greater degree of control. Consider this:
var url = getUrlFunction();
makeHttpRequest(url, function onResponse(data) {
dataHandler(data);
console.log("done");
}, function onError(err) {
errHandler(err);
console.log("uh oh");
});
showTheUserWeAreLoading();
// Or in node.js
var url = getUrlFunction();
makeHttpRequest(url, function onResponse(err, data) {
(err) ? handleErr(err): null;
dataHandler(data);
console.log("done");
});
showTheUserWeAreLoading();
It is not very intuitive that the showTheUserWeAreLoading function will (sometimes) happen before the HTTP request if fulfilled. This leaves much to be desired when rereading your own code.
The same code, but with the makeHttpRequest returns a promise:
var url = getUrlFunction(), prom = makeHttpRequest(url);
showTheUserWeAreLoading();
prom.then(function onSuccess(data) {
dataHandler(data);
console.log("done");
}, function onError(err) {
errHandler(err);
console.log("uh oh");
});
The promise object helps track the state of the operation. You assign handlers for when the operations reaches one of two states: Fulfilled or Rejected.
It should be noted that makeHttpRequest is a stand-in for $http() in AngularJS or $.ajax in jQuery. Before the standard for promises was created in the ECMAScript standard, each library (and library version) had its own opinion on which pattern you should/can use. AngularJS previously used the .success(<function>).error(<function>) naming pattern, while jQuery used .done(<function>).fail(<function>). These naming schemes have been depreciated a very long time ago, therefore making the current difference between libraries unnoticeable (thank you ECMAScript).
The $http API is based on the deferred/promise APIs exposed by the $q service.
1.then(successCallback, [errorCallback], [notifyCallback])
2.catch(errorCallback) – shorthand for promise.then(null, errorCallback)
3.finally(callback, notifyCallback)
$q promise method
As I plunge into studying Promises, my understanding has halted on the following question that I do not find discussed (all I find are specific discussions of the Promise constructor, and the Promise 'then' function - but not a discussion that compares their design patterns).
1. The Promise constructor
From the MDN documentation, we have this use of the Promise constructor (with my comment added):
new Promise(function(resolve, reject) { ... }); // <-- Call this Stage 1
Function object with two arguments resolve and reject. The first
argument fulfills the promise, the second argument rejects it. We can
call these functions, once our operation is completed.
2. The then function
Moving on to the then function that can be called on a Promise object (which returns a new Promise object), we have the following function signature as described by the documentation (with my comments added):
p.then(onFulfilled, onRejected);
Chaining
Because the then method returns a Promise, you can easily chain then
calls.
var p2 = new Promise(function(resolve, reject) {
resolve(1); // <-- Stage 1 again
});
p2.then(function(value) {
console.log(value); // 1
return value + 1; // <-- Call this Stage 2
}).then(function(value) {
console.log(value); // 2
});
My question
From the above code snippet, it seems clear to me that the value passed to the resolve function in Stage 1 (in the second occurrence of resolve - beneath (2), above) is passed on to the next stage (the first then function that follows in the same code snippet). There is no return value at Stage 1. However, it is the return value at Stage 2 that is passed on to the next stage after that (the second then function).
Is this lack of correspondence between the design pattern for the creation of a Promise, and the use of the then function on an existing promise (which also returns a Promise), just a historical fluke (one requires calling a callback but returns nothing, and the other returns a value but does not call a callback)?
Or am I missing an underlying reason why the Promise constructor utilizes a different design pattern than the then function?
Bergi's answer is excellent, and has been very helpful to me. This answer is complementary to his. In order to visualize the relationship between the Promise() constructor and the then() method, I created this diagram. I hope it helps somebody... maybe even me, a few months months from now.
The main idea here is that the "executor" function passed to the Promise() constructor sets tasks in motion that will set the state of the promise; whereas the handlers you pass to then() will react to the state of the promise.
(Code examples adapted from Jake Archibald's classic tutorial.)
This is a highly simplified view of how things work, leaving out many important details. But I think if one can keep a grip on a good overview of the intended purpose, it will help avoid confusion when one gets into the details.
A couple of selected details
The executor is called immediately
One important detail is that the executor function passed to the Promise() constructor is called immediately (before the constructor returns the promise); whereas the handler functions passed to the then() method will not be called till later (if ever).
Bergi mentioned this, but I wanted to restate it without using the terms a/synchronously, which can be confused if you're not reading carefully: The distinction between a function calling something asynchronously vs. being called asynchronously is easy to gloss over in communication.
resolve() is not onFulfill()
One more detail I'd like to emphasize, because it confused me for a while, is that the resolve() and reject() callbacks passed to the Promise() constructor's executor function are not the callbacks later passed to the then() method. This seems obvious in retrospect, but the apparent connection had me spinning in circles for too long. There is definitely a connection, but it's a loose, dynamic one.
Instead, the resolve() and reject() callbacks are functions supplied by the "system", and are passed to the executor function by the Promise constructor when you create a promise. When the resolve() function is called, system code is executed that potentially changes the state of the promise and eventually leads to an onFulfilled() callback being called asynchronously. Don't think of calling resolve() as being a tight wrapper for calling onFulfill()!
There is no correspondence between the Promise constructor and the then method because they are two independent things, designed for different purposes.
The Promise constructor is only used for promisifying1 asynchronous functions. Indeed, as you say, it is built on invoking resolve/reject callbacks to asynchronously send values, and there are no return values in that case.
That the Promise constructor itself does take this "resolver" callback (to which it synchronously passes resolve and reject) is in fact an enhancement of the older deferred pattern, and bears no intended similarity to the then callbacks.
var p = new Promise(function(res, rej) { | var def = Promise.Deferred();
setTimeout(res, 100); | setTimeout(def.resolve, 100);
}); | var p = def.promise;
The then callbacks in contrast are classical asynchronous callbacks, with the additional feature that you can return from them. They are being invoked asynchronously to receive values.
p.then(function(val) { … });
To sum up the differences:
Promise is a constructor, while then is a method
Promise takes one callback, while then takes up to two
Promise invokes its callback synchronously, while then invokes its callbacks asynchronously
Promise always invokes its callback,
then might not invoke its callbacks (if the promise is not fulfilled/rejected)
Promise passes the capabilities to resolve/reject a promise to the callback,
then passes the result value / rejection reason of the promise it was called on
Promise invokes its callback for the purpose of executing side effects (call reject/resolve),
then invokes its callbacks for their result values (for chaining)
Yes, both do return promises, though they share that trait with many other functions (Promise.resolve, Promise.reject, fetch, …). In fact all of these are based on the same promise construction and resolve/reject capabilities that also the Promise constructor provides, though that's not their primary purpose. then basically offers the ability to attach onFulfilled/onRejected callbacks to an existing promise, which is rather diametral to the Promise constructor.
That both utilise callbacks is just coincidential - not a historical fluke, but rather coadaption of a language feature.
1: Ideally, you would never need this because all natively asynchronous APIs return promises
Inspired by the previous answers (I'll address the part that was most confusing to me):
The resolve and reject arguments in the Promise constructor are not functions you define. Think of them as hooks that you get to embed into your async operation code (usually you resolve with success response and reject with failure reason) , so that javascript has a way to eventually mark the Promise as Fulfilled or Rejected depending on the outcome of your async operation; once that happens, the appropriate function you defined in then(fun1, fun2) is triggered to consume the Promise (either fun1(success_response) or fun2(failure_reason), depending on whether the Promise is Fulfilled/Rejected). Since fun1 and fun2 are plain old javascript functions (they just happen to take the future outcome of your async operation as arguments), they return values (which can be undefined if you don't explicitly return).
Also see great articles by Mozilla:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The whole point of the promise constructor executor function is to disseminate resolve and reject functions to non-promise-using code, to wrap it and convert it to use a promise. If you wanted to limit this to synchronous functions only, then yes, a return value from the function could have been used instead, but that would have been silly since the useful part is to disseminate the resolver and reject functions to code that actually runs later (way after the return), e.g. to callbacks passed in to some asynchronous API.
Here is the execution flow of Promise.
var p = new Promise((resolve, reject) =>{
console.log("1");
resolve("OK");
});
//The above code creates a promise and execustion starts immediately.
//it happens aynchronously. So the execution will not be blocked.
//Promise exustion will not wait for 'then' call on promise
console.log("2");
//The above line displays 2 on the console.
p.then((result)=>{
console.log("3");
console.log(result);
});
//The above code shoud not block execution. So it may print 4 first
// then 3
console.log("4");
I know how to create a promise in Kris Kowal's q with var defer = Q.defer();, calling defer.resolve(); and/or defer.reject() and return defer.promise. But reading the docs, it seem's there is an alternative way to create a promise...
From the docs:
Q.Promise(resolver)
Synchronously calls resolver(resolve, reject, notify) and
returns a promise whose state is controlled by the functions passed to
resolver. This is an alternative promise-creation API that has the
same power as the deferred concept, but without introducing another
conceptual entity.
If resolver throws an exception, the returned promise will be rejected
with that thrown exception as the rejection reason.
This is, what I've tried:
function () {
return Q.Promise(function (resolve, reject) {
(...do something...)
resolve(5); // or: reject(error);
});
}
But this doesn't work as expected!
Can someone give an example, how to use Q.Promise?
UPDATE:
Thanks for downvoting! I asked for an usage example, therefore a simple "you use it in a correct way" is more helpful! Btw: it fails silently and yes, I attached an error handler!
The reason, why the function is unnamed, is that I use it together with map and reduce to create a delayed chain of promises, but it seems, the resolver functions are never called... Therefore I asked for a (again) usage example...
Looking at your 2 examples, I'm guessing you are doing this:
var q = require('q');
Therefore Q.Promise won't work, but rather q.Promise will.