我正在 JavaScript 中的 for 循环内部进行异步 API 调用,但我不知道如何理解结果。这段代码对 API 进行了正确的调用(我通过查看 fiddler 知道了这一点)。
但是,当结果返回并在 console.log(translation) 中打印结果时,我只能看到最后一次 API 调用的结果。
我知道这是一个异步问题,但我应该如何最好地解决来自 xmlhttp2 的传入响应?
for (var j = 0; j <= current; j++) {
//some preprocessing
var xmlhttp2=new XMLHttpRequest();
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
var translation = xmlhttp2.responseText;
console.log(translation);
}
}
var sendparam = "http://api.foo.do.stuff.etc";
xmlhttp2.open("GET",sendparam,true);
xmlhttp2.send();
}
}
最佳答案
想通了。关闭 FTW
for (var j = 0; j <= current; j++) {
//some preprocessing
(function (j) {
var xmlhttp2=new XMLHttpRequest();
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
var translation = xmlhttp2.responseText;
console.log(translation);
}
}
var sendparam = "http://api.foo.do.stuff.etc";
xmlhttp2.open("GET",sendparam,true);
xmlhttp2.send();
})(j);
}
关于for循环内的Javascript异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28752895/