我的功能如下: -
function getCustomers() {
var len = 5;
var customers = new Array(len);
var _promises = [];
for (var i = 0; i < 5; i++) {
var p = dataService.get(sData, 'Customer').then(function (data) {
if (data.entity === "Customer" && data.id > 0) {
//*******I am in need to access customers by index (i)**********;
//customers[i] = data.id
return alert("loop "+i);
//***** Issue-this alerts 5 times "loop 6" ***///////
}
})
_promises.push(p);
}
}
$q.all(_promises).then(function () {
})
}
这是Angular(dataService)的样子
function read(data, entityName) {
var url = "API_Url"
return $http({
method: 'GET',
url: url,
})
.then(success)
.catch(exception);
function success(response){
return response.data;
}
}
答案 0 :(得分:1)
如果您使用的是ES6,则可以在循环中let
使用var
for (let i = 0; i < 5; i++) {
这样的let
然后使用for (let i=0;i<5;i++){
setTimeout(()=> console.log(i),0);
}
代码将起作用,就像这个简单的例子
let
由于for (var i=0;i<5;i++){
(function(j){
setTimeout(()=> console.log(j),0)
})(i);
}
关键字
如果不使用ES6,你应该像这样
制作一个i变量内部循环的副本<div class="col-lg-6">
<form action="/" method="post" class="dropzone needsclick dz-clickable"
id="demoUpload">
<div class="dz-message needsclick">
"Drop SVG Files Here or Click to Upload"
<br>
<span class="note needsclick">
"Only SVG filetypes are accepted. Rasterized img filetypes coming soon."
</span>
</div>
</form>
</div>
您可以在https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md#loops--closure
找到很好的解释