首页 > 解决方案 > 回调完成后从数据表中删除

问题描述

我有一个数据表,每个表上都有一个复选框,还有一个按钮可以触发我对该行的操作。我想在我的操作完成后删除该行。

for (i = 0; i < checkedBoxes.length; i++) {
    var chk = checkedBoxes[i];
    var tdef = chk.closest("tr").querySelectorAll('td');
    var myThing = tdef[1].innerHTML;

    service.doSomething(myThing, function (result) {
        service.doSomethingElse();

        // I would like to remove this row once I'm done with this row
        //browseDataTable.row($(chk).parents('tr')).remove().draw();
    });
}

我知道我不应该在循环遍历它时删除该行。所以我打算只收集每一行的索引,当一切都完成后,我可以删除它,如下所示:

var myArr = new Array();
for (i = 0; i < checkedBoxes.length; i++) {
    service.doSomething(myThing, function (result) {
        service.doSomethingElse();

        myArr.push(i);
    })  // Chrome said 'then' is undefined, so how do I chain callback here?
    .then(function () {
        // Remove all rows at index in myArr
    });
}

该服务不是异步服务,它是一个 ASMX 服务。

标签: javascript

解决方案


您正在使用您的服务,就像一个带有回调Promise 的函数。那么它是哪一个?它需要回调,还是返回 Promise?

看起来它没有返回 Promise,因为您正在尝试链接.then()并且它是未定义的。

The service isn't async那你为什么要给它一个回调并尝试链接 a .then(),如果它是同步的?

无论如何,解决问题的一种简单方法是使用let,它将为每个循环创建一个范围。

目前 :

for (i = 0; i < checkedBoxes.length; i++) { // i is a global (window) variable, that's bad
    service.doSomething(myThing, function (result) {
        service.doSomethingElse();
        myArr.push(i); // i will always be checkboxes.length
    })
}

通过使用 let :

for (let i = 0; i < checkedBoxes.length; i++) { // i is in the local scope
    service.doSomething(myThing, function (result) {
        service.doSomethingElse();
        myArr.push(i); // the value of i will be different (correct) each time
    })
}

推荐阅读