我有一个元素数组,我需要循环它们,每次传递时从服务器获取一个值。通过以下代码我得到 由于 forEach 循环中的异步调用,所有结果混合在一起。我需要以与数组中相同的顺序显示结果。
var en_devices= [
["72", "Device 1"],
["73", "Device 2"],
["74", "Device 3"],
["75", "Device 4"],
["76", "Device 5"],
["5158", "Device 6"]
];
en_devices.forEach(element => {
$.get('/check-energy/'+element[0], function(data){
content = "<div class='service'>"+element[1]+"</div> <div class='watt'>"+data+"</div><br/>";
$('#description-en').append(content);
});
});
最佳答案
如果$.get
是jQuery.get()然后它返回一个 promise ,您可以使用异步编程。
正如@CherryDT所说,在async
函数中使用它。如果您没有,请使用 IIFE - 立即调用函数表达式:
(async () => {
for (let element of en_devices) {
const data = await $.get('/check-energy/' + element[0]);
const content = "<div class='service'>" + element[1] + "</div> <div class='watt'>" + data + "</div><br/>";
$('#description-en').append(content);
}
})();
更新:
正如 @huyts 所指出的,上述方法一次调用一个 API。要使其并行,请使用 Promise.all
:
(async () => {
const promises = en_devices.map(element =>
$.get('/check-energy/' + element[0])
.then(data => [element[1], data])
);
const results = await Promise.all(promises);
for (let result of results) {
const content = "<div class='service'>" + result[0] + "</div> <div class='watt'>" + result[1] + "</div><br/>";
$('#description-en').append(content);
}
})();
关于javascript - forEach 循环有序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631704/