Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - Difference between defer().promise and Promise

I know defer separates promises states control and process, here using Q as an example, the promise returned by Q.defer().promise and Q.Promise is totally different, why designing in this way? and what's the difference between these two "Promise"

Thanks in advance

PS: I'm currently working on a Promise library, issuses and PRS are welcomed: https://github.com/jiananshi/Promise-polyfill

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, this is about the promise resolution source. Q and a bunch of other libraries offer two APIs:

  • The legacy defer API - in which you create a deferred that you can .resolve(value) and it has a promise you can return.
  • The promise constructor - which is the modern API in which you create the promise from a completion source.

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

Why do we need two APIs?

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.

Throw safety

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 throws 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...