循环中的JavaScript异步调用
问题描述:
我正在面对javascript中的异步调用问题,并将错误(不是预期的)值传递给该函数。请参阅伪代码:循环中的JavaScript异步调用
i=0;
while(i<10){
var obj= {something, i};
getcontent(obj); //(<--- getcontent is async function/problem)
i++;
}
所有getcontent异步调用都使用最后的i = 9值,这不是我想要实现的。
如何/我应该如何处理这种异步调用,并在每次调用中获取正确的/传递正确的i值?
答
<script>
var i = 0;
while (i < 5) {
setTimeout(function() {
getcontent()
}, 2000);
i++;
}
function getcontent(){
alert()
}
</script>
希望它会帮助你
答
如何:
async function loop(){
var i: number = 0;
while (i < 10) {
(async function() {
var obj = { "@": "fd", "#": i };
await getcontent(obj); //(<--- getcontent is async function/problem)
i++;
})();
}
}
答
我认为这是你在找什么~~
var funcs = [];
var i = 0;
while (i < 10) {
funcs[i] = (function(index) {
return function() {
var obj = { '@': 'fd', 'index': index};
return getcontent(obj); //(<--- getcontent is async function/problem)
};
}(i));
i++;
}
function getcontent(obj) {
console.log("My value: " + obj.index);
};
funcs.forEach(function (item) { item(); });