首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对每一个没有按正确顺序开火的人

对每一个没有按正确顺序开火的人
EN

Stack Overflow用户
提问于 2018-03-02 15:57:43
回答 2查看 194关注 0票数 0

晚上好。

我目前正在开发一个应用程序,它使用twitch。

这是我第一次不得不使用forEach JS命令。但由于某些原因,我看不出这是一种混乱,就好像每个数组都没有按正确的顺序触发,而且函数有时会在触发下一个数组的元素之前执行几次。

我建立了一个代码库来解决这个问题:

https://codepen.io/Hadrienallemon/pen/bLZJeX

正如您在笔中看到的那样,如果您在测试按钮上单击几次,结果并不总是按正确的顺序。

下面是代码:

HTML:

代码语言:javascript
复制
<button id="button">test button</button>
<div class="wrapper"></div>

CSS:

代码语言:javascript
复制
html,body{
  height : 100%;
  width : 100%;
}

.wrapper{
  height : 90%;
  width : 100%;
}

.awnser{
  background-color : tomato;
  margin : 50px auto;
  width : 60%;
  min-height : 10%;

}

联署材料:

代码语言:javascript
复制
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>");

    }) 
  })  
})
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-02 16:10:32

$.getJSON异步。您的forEach以给定的顺序启动调用,但它们完全可以以任何顺序完成,完全混乱。

如果您想按顺序处理它们的完成,可以将每个承诺从$.getJSON保存到一个数组中,等待它们与$.when一起完成(它们将并行运行,但您的回调将在它们完成后才运行),然后处理结果:

代码语言:javascript
复制
$.when.apply($, lives.map(element => $.getJSON(/*...*/))
.done((...results) => {
    // All calls are done, process results
    results.forEach(result => {
        // ...
    });
});

jQuery的$.when将调用您的done回调,并为传递它的每个承诺设置一个参数。在上面,我们通过rest参数将它们收集到一个数组中,然后循环遍历它。

或者使用使用arguments伪数组的ES2015前语法:

代码语言:javascript
复制
$.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) {
        // ...
    });
});
票数 1
EN

Stack Overflow用户

发布于 2018-03-02 16:17:03

代码语言:javascript
复制
// Your code:
/*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>");

    }) 
  })  
})*/

// You need to use JQuery's method to get the data back in promises to know the order in which they are received and map the data together:
const lives = ["nat_ali","krayn_live","streamerhouse","merry"];
$(".wrapper").empty();
const streams = lives.map((val) => {
  return $.getJSON(`https://wind-bow.glitch.me/twitch-api/streams/${element}?callback=?`;
});
const users = lives.map((val) => {
  return $.getJSON(`https://wind-bow.glitch.me/twitch-api/users/${element}?callback=?`;
});

$.when(streams).then(
  (streamsData) => {
    // Do what you need to for when the streamsData (array) is correlated to the array indices for the "lives" array defined above.
  },
  (err) => { /* handle API failures */ }
);
  
$.when(users).then(
  (usersData) => {
    // Do what you need to do for the usersData (array) that is correlated to the array indices for the "lives" array defined above.
  }
);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49072767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档