0

This is my code ,

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

There are two condition inside loop , one is checking name != null and api call inside , the next is value.flag . I just want to reach to second condition after api call complete .

asynts
  • 2,213
  • 2
  • 21
  • 35
zey
  • 5,939
  • 14
  • 56
  • 110

3 Answers3

0

you can use done function when ajax request completes

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});
Barry
  • 3,303
  • 7
  • 23
  • 42
fuzzybear
  • 2,325
  • 3
  • 23
  • 45
0

Take a look at the docs: https://api.jquery.com/jquery.ajax

I think what you're looking for is the following:

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

With that in mind, you'll have to move the value.flag check to the callbacks:

$.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) {}
      })
  }
)};
Hristo
  • 45,559
  • 65
  • 163
  • 230
0

If I understand, you want all Ajax calls and iterations completed after doing something, so I think you want something like this:

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) {}
      }

    }
Emeeus
  • 5,072
  • 2
  • 25
  • 37
  • according to your code , I think if `value.name == null` , then the second condition `value.flag` cannot reach , am I right ? – zey Aug 16 '18 at 17:31
  • @zey Yes, but if value.name == null not all calls are made – Emeeus Aug 16 '18 at 17:37
  • please recheck my code ,even `value.name` is null or not , should reach the second condition . – zey Aug 16 '18 at 17:39
  • @zey I'm not sure if I understand, I've updated the answer, in that way we could only reach `if (value.flag) {}` if all requests and iterations are made. Am I right? – Emeeus Aug 16 '18 at 17:43