晚上好。
我目前正在开发一个使用 twitch API 的应用。
我第一次不得不使用 forEach JS 命令。但由于某种原因,我无法弄清楚,它似乎有点困惑,好像每个都没有以正确的顺序触发,并且好像该函数有时在下一个数组的元素被触发之前执行多次。
我构建了一个代码笔来解决这个问题:
https://codepen.io/Hadrienallemon/pen/bLZJeX
正如您在笔中看到的,如果您多次单击测试按钮,结果并不总是按正确的顺序排列。
代码如下:
HTML:
<button id="button">test button</button>
<div class="wrapper"></div>
CSS:
html,body{
height : 100%;
width : 100%;
}
.wrapper{
height : 90%;
width : 100%;
}
.awnser{
background-color : tomato;
margin : 50px auto;
width : 60%;
min-height : 10%;
}
JS:
var lives = ["nat_ali","krayn_live","streamerhouse","merry"];
$("button").on("click",function(){
lives.forEach(function(element){
$(".wrapper").empty();
$.getJSON("https://wind-bow.glitch.me/twitch-api/streams/"+ element +"?callback=?",function(quote){
if (quote.stream != null){
$(".wrapper").append("
<div class = 'awnser'>
<p>"+quote.stream.game+"</p>
</div>");
}
else{
$(".wrapper").append("
<div class = 'awnser'>
<span class = 'circle' style ='text-align : right'>
<p style = 'display : inline-block;'>offline</p>
</span>
</div>");
}
})
$.getJSON("https://wind-bow.glitch.me/twitch-api/users/"+ element +"?callback=?",function(quote){
console.log(quote.logo);
$(".awnser:last-child").append("
<div style ='width : 10%; height : 10%;'>"+ quote.display_name +"
<img src = '"+quote.logo+"' style = 'max-width : 100%;max-height : 100%;'></div>");
})
})
})
最佳答案
$.getJSON
是异步。您的 forEach
按给定顺序开始调用,但它们可以以任何顺序完成,完全困惑。
如果你想按顺序处理它们的完成,你可以将 $.getJSON
中的每个 Promise 保存在一个数组中,用 $.when
等待它们完成(它们将并行运行,但在它们全部完成之前您的回调不会运行),然后处理结果:
$.when.apply($, lives.map(element => $.getJSON(/*...*/))
.done((...results) => {
// All calls are done, process results
results.forEach(result => {
// ...
});
});
jQuery 的 $.when
将调用您的 done
回调,并为您传递的每个 promise 提供一个参数。在上面,我们通过剩余参数将它们收集在一个数组中,然后循环遍历它。
或者使用 ES2015 之前的语法,使用 arguments
伪数组:
$.when.apply($, lives.map(function(element) { return $.getJSON(/*...*/)})
.done(function() => {
var results = Array.prototype.slice.call(arguments);
// All calls are done, process results
results.forEach(function(result) {
// ...
});
});
关于javascript - 对于每个不按正确顺序发射的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072767/