解析承诺返回空对象(Parse promise returns empty object)

2019-10-23 07:01发布

我遍历数组,但每次迭代,我打电话异步方法。

下面是代码

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":{}}}

我应该怎么解决的承诺,让我得到所需的输出?

Answer 1:

问题是,里面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
}); 


文章来源: Parse promise returns empty object