Why are promises being resolved before success callbacks are run?

时间:2015-07-29 00:26:36

标签: javascript jquery promise jquery-deferred

So I have code that looks like this

<ul style="position: relative;">
    <li class="nav-menu-item-357 main-menu-item  menu-item-even menu-item-depth-0 new_dropdown_style menu-item menu-item-type-custom menu-item-object-custom">
        <a href="#" class="menu-link main-menu-link sf-with-ul">    
            <span>Issues</span>
        </a>
    </li>
</ul>

var nodes = partition.nodes(root); //render

I get an error on this line -

var addExpenses = function(parent) {
    return function(data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                var expenditure = data[i].RestrictedExpenditure;
                expenditure = parseFloat(expenditure);
                var child = {level: 4, name: data[i].Name, size: expenditure, children: []};
                parent.children.push(child);
            }
        }
    }
}

var addSubActivities = function(parent) {
    return function(data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                var expenditure = data[i].Expenditure;
                expenditure = parseFloat(expenditure);
                if (expenditure < 0) {
                    expenditure = -expenditure;
                }
                var child = {level: 3, name: data[i].Name, size: expenditure, children: []};
                parent.children.push(child);
                subActivitiesDfds.push($.getJSON("http://localhost:8080/district/1/subActivities/" + data[i].Code + "/expenses", addExpenses(child)));
                // subActivitiesDfds.push(dfd);
            }
        }
    }
}

for (var i = 0; i < data.length; i++) {
    var expenditure = data[i].Expenditure;
    expenditure = parseFloat(expenditure);
    total += expenditure;
    var child = {level: 2, name: data[i].Name, size: expenditure, children: []};
    root.children.push(child);

    subActivitiesDfds.push($.getJSON("http://localhost:8080/district/1/activities/" + data[i].Code + "/subActivities", addSubActivities(child)));
    // subActivitiesDfds.push(dfd);
}
root.size = total;


$.when.apply($, subActivitiesDfds).done(function() {
  • children is undefined. This is happening because partition.nodes(root) destroys the parent property, which is happening because the list of promises is resolved before the addExpenses callback is called.

Why?

1 个答案:

答案 0 :(得分:1)

出现问题是因为在执行$.when.apply($, subActivitiesDfds)时,subActivitiesDfds仅填充了顶级承诺。生成下一级承诺的代码仅在最高级别承诺得到满足时才会运行。

要修复,您需要:

  • 确保addSubActivities()在所有处理完成后返回承诺。
  • 在两个地方替换$.getJSON(..., fn) $.getJSON(..., ).then(fn)

您还会发现array.map()可以方便地构建承诺数组。

尝试:

var addExpenses = function(parent) {
    return function(data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                var child = {
                    level: 4, 
                    name: data[i].Name, 
                    size: parseFloat(data[i].RestrictedExpenditure),
                    children: []
                };
                parent.children.push(child);
            }
        }
    }
}

var addSubActivities = function(parent) {
    return function(data) {
        if (data) {
            var promises = data.map(function(item) {
                var child = {
                    level: 3,
                    name: item.Name,
                    size: Math.abs(parseFloat(item.Expenditure)),
                    children: []
                };
                parent.children.push(child);
                return $.getJSON("http://localhost:8080/district/1/subActivities/" + item.Code + "/expenses")
                .then(addExpenses(child));
            });
            return $.when.apply($, promises);
        } else {
            return $.when();//resolved promise
        }
    }
}

var promises = data.map(function(item) {
    var child = {
        level: 2,
        name: item.Name,
        size: parseFloat(item.Expenditure),
        children: []
    };
    root.children.push(child);
    total += child.size;
    return $.getJSON("http://localhost:8080/district/1/activities/" + item.Code + "/subActivities").then(addSubActivities(child));
});
root.size = total;

$.when.apply($, promises).then(function() {
    var nodes = partition.nodes(root); //render
});

顶级promises数组仍然仅填充顶级承诺,但现在链式.then()确保每个承诺仅在其所有同步和异步子活动时才会解决已经完成了。