我有一个数据表,每个表上都有一个复选框,以及一个将触发该行操作的按钮。我想在完成操作后删除该行。
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服务。
答案 0 :(得分:0)
您正在使用服务,就像带有回调和 Promise的函数一样。那是什么呢?它需要回调还是返回Promise?
它似乎没有返回Promise,因为您正在尝试链接.then()
且未定义。
The service isn't async
,那么为什么要给它回调并尝试链接.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
})
}