How to access return value from deferred object?

别来无恙 提交于 2019-12-22 05:54:22

问题


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();
        })

});


来源:https://stackoverflow.com/questions/14254503/how-to-access-return-value-from-deferred-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!