How to access return value from deferred object?

2019-04-30 04:21发布

问题:

I have the following code that uses $.getJSON inside the repository to return some data that is then used by other functions.

$.when(
    repository.getUserDetails().done(dataPrimer.getUserDetails),

    $.Deferred(
        function (deferred) {
           deferred.resolve();
        }
    )

).done(
   function () {
       repository.getUserPolicyTitles().done(dataPrimer.getUserPolicyTitles);
   },

   function () {
       repository.getUserPage().done();
   }
);

This works but I need to return a value from: repository.getUserDetails().done(dataPrimer.getUserDetails) that can be used as a parameter to: repository.getUserPage().done();

The dataPrimer module for getUserDetails currently looks like this:

var getUserDetails = function (jsonString) {
    var object = parser.parse(jsonString);
    userDetails.userName = object.user.userName;
    userDetails.lastPolicyWorkedOn = object.user.lastPolicyWorkedOn;
    return userDetails.lastPolicyWorkedOn;
}

I have tried a few things such as .pipe() with no joy and want to be confident that I'm using a decent approach so I'm looking for the "best practice" way to return the parameter and use it in the repository.getUserPage() function please?

回答1:

You should use "then" . The "data" in example -- data returned by "getUserPolicyTitles" function.

$.when(
    repository.getUserDetails().done(dataPrimer.getUserDetails),

    $.Deferred(
        function (deferred) {
           deferred.resolve();
        }
    )

).done(function() {

    repository
        .getUserPolicyTitles()
        .done(dataPrimer.getUserPolicyTitles)
        .then(function(data) {
            repository.getUserPage().done();
        })

});