解析承诺返回空对象

时间:2015-06-07 03:39:58

标签: javascript jquery parse-platform promise

我正在迭代一个数组,但是每次迭代,我都会调用一个异步方法。

以下是代码

var getTaskResponse = function(displayedWidgetId) {

    var promises = [];
    // var promise = new Parse.Promise();
    jQuery.ajax({
        type: "POST",
        url: 'https://api.parse.com/1/functions/getWidgetResponse',
        data: {
            "groupWidgetId": displayedWidgetId
        },
        beforeSend: function(request) {
            request.setRequestHeader("X-Parse-Application-Id", parse_ids.app_id);
            request.setRequestHeader("X-Parse-REST-API-Key", parse_ids.rest_api);
        }
    })
    .then(function(response){
        var promise = new Parse.Promise();
        var taskIssuedTo = {},

            taskObj = {},
            finalObj = {},
            subTasks = [],
            taskResponse = response.result;


        taskResponse.forEach(function(widgetResponseObj,index) {
            var issuedTo = widgetResponseObj.answeredBy.objectId,
                taskResponseObj = JSON.parse(widgetResponseObj.widgetResponse),
                taskSelected = taskResponseObj.taskSelected,
                date = taskResponseObj.date;

            (function(userId){
                getUsersName(userId).then(function(userName){
                    if (typeof taskIssuedTo[taskSelected] === "undefined") {
                        taskIssuedTo[taskSelected] = [];
                        subTasks = [];
                    }

                    subTasks.push({
                        "user" : userName.result.name,
                        "date" : date
                    });

                    taskIssuedTo[taskSelected] = subTasks;
                    taskObj[taskSelected] = taskIssuedTo[taskSelected];
                });
            }(issuedTo));  
        });
        promise.resolve(taskObj);        
        return promise;
    })
    .then(function(obj){
        console.log("After Promise Return :: "+JSON.stringify(obj));
    });
}

在上面for-each loop getUsersName 是被调用的方法。当我打印已解决的承诺时,这就是我得到的

承诺返回后:: {"_resolved":true,"_rejected":false,"_resolvedCallbacks":[],"_rejectedCallbacks":[],"_result":{"0":{}}}

我应该如何解决这个承诺,以便获得所需的输出?

1 个答案:

答案 0 :(得分:0)

问题是在taskResponse.forEach内你正在调用异步的getUserName。你知道,当它完成更多工作时,你的外部功能不会等待完成。

这是一种方法:

var getTaskResponse = function (displayedWidgetId) {
    var promiseToReturn = new Parse.Promise();

    // var promise = new Parse.Promise();
    jQuery.ajax({
        type: "POST",
        url: 'https://api.parse.com/1/functions/getWidgetResponse',
        data: {
            "groupWidgetId": displayedWidgetId
        },
        beforeSend: function (request) {
            request.setRequestHeader("X-Parse-Application-Id", parse_ids.app_id);
            request.setRequestHeader("X-Parse-REST-API-Key", parse_ids.rest_api);
        }
    }).then(function (response) {
        var taskIssuedTo = {},

        taskObj = {},
        finalObj = {},
        subTasks = [],
            taskResponse = response.result;


        var promisesToWaitOn = [];

        taskResponse.forEach(function (widgetResponseObj, index) {
            var issuedTo = widgetResponseObj.answeredBy.objectId,
                taskResponseObj = JSON.parse(widgetResponseObj.widgetResponse),
                taskSelected = taskResponseObj.taskSelected,
                date = taskResponseObj.date;

            promisesToWaitOn.push(function (userId) {
                return getUsersName(userId).then(function (userName) {
                    if (typeof taskIssuedTo[taskSelected] === "undefined") {
                        taskIssuedTo[taskSelected] = [];
                        subTasks = [];
                    }

                    subTasks.push({
                        "user": userName.result.name,
                            "date": date
                    });

                    taskIssuedTo[taskSelected] = subTasks;
                    taskObj[taskSelected] = taskIssuedTo[taskSelected];
                });
            }(issuedTo));
        });
        return Parse.Promise.when(promisesToWaitOn).then(function () {
            promiseToReturn.resolve(taskObj);
        });
    });
    return promiseToReturn;
}

如果要访问函数的结果,可以这样做:

getTaskResponse(widgitId).then(function(taskObj) {
     // Here is where you can do something with the generated taskObj
});