ajax请求没有同步执行?

时间:2017-09-05 18:41:17

标签: javascript jquery ajax

我有这段代码:

let channels = ["freecodecamp","test_channel","ESL_SC2"];
    channels.map(function(channel) {
      function genUrl(type, name) {
        return 'https://wind-bow.gomix.me/twitch-api/' + type + '/' + name + '?callback=?';
      }
        $.ajax({ // 2 ajax requests
          url: genUrl("streams", channel),
          dataType: 'jsonp',
          success: function(data) {
                console.log("data = ",data)
            setState(data);      
            $.ajax({
              url: genUrl("channels", channel),
              dataType: 'jsonp',
              success: function(res) { // res = result
                console.log("res = ",res)
                setState(res);
              },
            });
          },
        });
    });

但是当我记录时,生成的ajax没有同步执行。在地图上,我期望ajax req在req(相同的索引)上执行相同的通道,但它不是,因为结果是乱码的。 让我们说第一个ajax,地图执行就像["ESL_SC2","freecodecamp","test_channel"] 在第二个: ["freecodecamp","test_channel","ESL_SC2"] 我希望结果与声明的索引相同?

let channels = ["freecodecamp","test_channel","ESL_SC2"];

我的结果日志样本:

data =  {mature: false, status: "RERUN: Zest vs. data =  {mature: false, status: "RERUN: Zest vs. Trust [PvP] - Group B Elimination Map 2 - IEM Gyeonggi 2016", broadcaster_language: "en", display_name: "ESL_SC2", game: "StarCraft II", …}background: nullbanner: nullbroadcaster_language: "en"created_at: "2012-05-02T09:59:20Z"delay: nulldisplay_name: "ESL_SC2"followers: 192328game: "StarCraft II"language: "en"logo: "https://static-cdn.jtvnw.net/jtv_user_pictures/esl_sc2-profile_image-d6db9488cec97125-300x300.jpeg"mature: falsename: "esl_sc2"partner: trueprofile_banner: "https://static-cdn.jtvnw.net/jtv_user_pictures/esl_sc2-profile_banner-f8295b33d1846e75-480.jpeg"profile_banner_background_color: "#050506"status: "RERUN: Zest vs. Trust [PvP] - Group B Elimination Map 2 - IEM Gyeonggi 2016"updated_at: "2017-09-05T18:05:46Z"url: "https://www.twitch.tv/esl_sc2"video_banner: "https://static-cdn.jtvnw.net/jtv_user_pictures/esl_sc2-channel_offline_image-5a8657f8393c9d85-1920x1080.jpeg"views: 68095345_id: 30220059_links: {self: "https://api.twitch.tv/kraken/channels/esl_sc2", follows: "https://api.twitch.tv/kraken/channels/esl_sc2/follows", commercial: "https://api.twitch.tv/kraken/channels/esl_sc2/commercial", stream_key: "https://api.twitch.tv/kraken/channels/esl_sc2/stream_key", chat: "https://api.twitch.tv/kraken/chat/esl_sc2", …}__proto__: Object
 data =  {mature: false, status: "TESTING  TESTING   TESTING", broadcaster_language: null, display_name: "test_channel", game: null, …}
 data =  {mature: false, status: "Some GoLang Today #go #golang #youtube", broadcaster_language: "en", display_name: "FreeCodeCamp", game: "Creative", …}
res =  {stream: null, _links: {…}}
res =  {stream: {…}, _links: {…}}
res =  {stream: null, _links: {…}}

我想在这里说的是,在第一个数据索引上,让我们说它是“freecodecamp”作为参数的结果,但是在第一个索引res上它不是“freecodecamp”被评估,它是“test_channel”,所以在执行地图时,我假设响应很长,所以它会评估下一个索引?换句话说,第一个数据索引和第一个res索引不匹配

2 个答案:

答案 0 :(得分:0)

您没有在ajax块中将异步设置为false。与此类似:

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

但一般来说,你不应该依赖同步的ajax调用,而应该以可以异步执行的方式编写。

答案 1 :(得分:0)

我使用async / await解决了这个问题,并在第二个req上返回第一个req的结果。这是代码:

$.ajax({ // 2 ajax requests
          url: genUrl("channels", channel),
          async: false,
          dataType: 'jsonp',
          success: async function(data) {
            debugger;
            $.ajax({
              url: genUrl("streams", channel),
              async: false,
              dataType: 'jsonp',
              success: async function(res) { // res = result
                debugger;
                console.log("data+res = ",{data, res})
                await setState({data, res});
              },
            });
          },
        });

我正在反应中使用它,我认为反应尝试渲染第一个ajax产生的每个数据,所以第二个ajax req没有按照我的预期进行评估,但我不确定。无论如何。试试吧。祝你好运!