Reputation: 456
I know defer separates promises states control and process. Using Q as an example, the promise returned by Q.defer().promise
and Q.Promise
are totally different. Why is it designed in this way? And what's the difference between these two Promises?
Upvotes: 24
Views: 9773
Reputation: 276296
Well, this is about the promise resolution source. Q and a bunch of other libraries offer two APIs:
defer
API - in which you create a deferred that you can .resolve(value)
and it has a promise you can return.Roughly doing:
var d = Q.defer();
setTimeout(function(){ d.resolve(); }, 1000);
return d.promise;
Is the same as:
return new Promise(function(resolve, reject){
setTimeout(resolve, 1000);
});
so you might be asking
Well, the defer API came first. It's how some other languages deal with it, it's how the papers deal with it and it's how people used it first - however - there is an important difference between the two APIs. The promise constructor is throw safe.
Promises abstract exception handling and are throw safe. If you throw inside a promise chain it will convert that exception into a rejection, quoting the spec:
If either onFulfilled or onRejected throws an exception e, promise2 must be rejected with e as the reason
Let's assume you're parsing JSON from an XHR request:
function get(){
var d = Q.defer();
if(cached) { // use cached version user edited in localStorage
d.resolve(JSON.parse(cached));
} else { // get from server
myCallbackApi('/foo', function(res){ d.resolve(res); });
}
}
Now, let's look at the promise constructor version:
function get(){
return new Promise(function(resolve, reject){
if(cached) { // use cached version user edited in localStorage
resolve(JSON.parse(cached));
} else { // get from server
myCallbackApi('/foo', resolve);
}
});
}
Now, assume somehow your server sent you invalid JSON (or the user edited it to an invalid state) and you cached it.
In the defer version - it throws synchronously. So you have to generally guard against it. In the bottom version it does not. The top version usage would look like:
try{
return get().catch(function(e){
return handleException(e); // can also just pass as function
});
} catch(e){
handleException(e);
}
In the bottom version - the promise constructor will convert throw
s to rejections so it is enough to do:
return get().then(function(e){
return handleException(e);
});
Preventing a whole class of programmer errors from ever happening.
Upvotes: 40