首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript循环等待api调用完成

Javascript循环等待api调用完成
EN

Stack Overflow用户
提问于 2018-08-17 01:11:57
回答 2查看 882关注 0票数 0

这是我的代码

$.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) {}
});

在循环内部有两个条件,一个是检查里面的name != null和api调用,另一个是value.flag。我只想在api调用完成后达到第二个条件。

EN

回答 2

Stack Overflow用户

发布于 2018-08-17 01:14:58

当ajax请求完成时,您可以使用done函数

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

Stack Overflow用户

发布于 2018-08-17 01:18:45

看看文档:https://api.jquery.com/jquery.ajax

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

$.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) {}
      })
  }
)};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51882223

复制
相关文章

相似问题

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