Javascript循环等到api调用完成

时间:2018-08-16 17:11:57

标签: javascript jquery ajax

这是我的代码

client = discord.Client()
await client.wait_until_ready()
channels = []
for server in client.servers:
  for channel in server.channels:
     channels.append(channel)
     # If you have your discord.Message object (message) and
     # command you want to send (command_str) you could then:
     # await client.send_message(message.channel, command_str)
# channels will now be populated with all the possible channels

循环中有两种情况,一种是检查$.each(result, function (index, value) { if (value.name != null) { $.ajax({ // myApi call code }); } // I only want reach here after api call finish if (value.flag) {} }); 和api调用,第二种是name != null。我只想在api调用完成后达到第二个条件。

3 个答案:

答案 0 :(得分:0)

您可以在ajax请求完成时使用完成功能

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

答案 1 :(得分:0)

看看文档:{​​{3}}

我认为您正在寻找以下内容:

$.ajax({
  // options
})
  .done(function (response) {
    // do something with the response
  })
  .fail(function (response) {
    // handle the error case
  })
  .always(function (response) {
    // do something always at the end of the sequence
  })

请牢记这一点,您必须将value.flag检查移至回调:

$.each(result, function (index, value) {
  if (value.name != null) {
    $.ajax({ /* options */ })
      .done(function (response) {
        // this check will happen only if the request succeeds
        if (value.flag) {}
      })
      .fail(function (response) {
        // this check will happen only if the request fails
        if (value.flag) {}
      })
      .always(function (response) {
        // this check will always happen after the request
        if (value.flag) {}
      })
  }
)};

答案 2 :(得分:0)

如果我理解的话,您希望所有Ajax调用在完成某些操作后完成迭代,所以我认为您需要这样的内容:

var i = result.length - 1;
$.each(result, function(index, value) {
      if (value.name != null) {
        $.ajax({
          //code
        }).done(function() {
          i--;//<-- subtract 1 if ajax is completed
        });
      } else {
        i--;//<-- subtract 1 if value.name == null
      }
      if (!i) {//<-- it's true only if all ajax are completed and all iterations are made
        if (value.flag) {}
      }

    }