简体   繁体   中英

How to return a promise from JavaScript function?

Imagine I have X , Y and Z functions, all returning promises and ready to chain. What I want to do is to notify about the progress after they are complete and handle error. What is better to write and why (what are the consequences):

A.

function my_func(index, size){
    return X
        .then(Y)
        .then(Z)
        .then(
           function(data){
               var dfd = new $.Deferred();
               dfd.notify("progress", index / size, 'OK');
               dfd.resolve(data);
               return dfd.promise();
           },
           function(){
               return handleError(arguments, size, index);
           }
        );
}

or

B.

function my_func(index, size){
    var dfd = new $.Deferred();
    X
    .then(Y)
    .then(Z)
    .then(
        function(data){
            dfd.notify("progress", index / size, 'OK');
            dfd.resolve(data);
        },
        function(){
            return handleError(arguments, size, index);
        }
    )
    return dfd.promise();
}

Also, what is the difference between:

X.then(Y).then(Z);

and:

$.when(X).then(Y).than(Z);

If $.when part is unnecessary, why doeas it exist in jQuery at all?

The latter is unnecessary. It's just extra cruft. $.when is useful for converting values to promises and for aggregation.

Here is an average $.when use case:

$.when($.get(...),$.get(...)).then(function(firstResult,secondResult){
     // access both results here
}); 

You can use both results here, both have finished.

As for the first question - basically B. The first option is the deferred anti pattern and is better avoided. See the link to it question on why.

The main difference would be that you are relying on X to be an object that has the method then . Passing a non Deferred/promise object to $.when will treat it as a resolved Deferred , which personally I would prefer as it makes the coupling between the functions more loose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM