JavaScript行为怪异(可能是由于其异步性质)
我在JS中有这段代码,如下所述JavaScript行为怪异(可能是由于其异步性质),javascript,angularjs,Javascript,Angularjs,我在JS中有这段代码,如下所述 for (id in ids) { if (id needs to be called) { console.log(id); // statement 1 $http.post('someEndpoint', {id : id}).then(function success(response) { console.log(id); // statement 2 someD
for (id in ids) {
if (id needs to be called) {
console.log(id); // statement 1
$http.post('someEndpoint', {id : id}).then(function success(response) {
console.log(id); // statement 2
someDataStructure[id].data = response.data;
});
}
}
假设ids=[1,2,3]
,在语句1中,1,2,3
打印在控制台上。在语句2中,打印了3
。这显然不太理想,我正在丢失12
的数据。另外,我必须补充一点,端点正在获取对123
的请求,所以在这一点上,我真的很困惑。如果有人能给我一些启示,帮助我理解如何解决这个问题,那就太好了。将id
包装成:
您也可以简单地使用一个forEach
循环,它将自动关闭:
ids.forEach(function(id) {
if (/*id needs to be called*/) {
console.log(id); // statement 1
$http.post('someEndpoint', {id : id}).then(function success(response) {
console.log(id); // statement 2
someDataStructure[id].data = response.data;
});
}
});
如果
ids
是一个数组,请使用for(让id中的索引)
,然后使用let id=ids[index]
。如果ids
是一个数组,则不应在中使用。将其更改为id.forEach(function(id){…})
,您就可以设置了。@斜视是的,我知道这个问题,这就是为什么我说“确保调用id
,而不是id
的索引。为了避免混淆,我修改了我的答案。使用ES6let
,我们可以摆脱闭包。谢谢!我会尝试一下,并随时通知您:)
ids.forEach(function(id) {
if (/*id needs to be called*/) {
console.log(id); // statement 1
$http.post('someEndpoint', {id : id}).then(function success(response) {
console.log(id); // statement 2
someDataStructure[id].data = response.data;
});
}
});