0

I was searching how to execute code in the order that it's written (since I need an effect to only happen if some condition is met) and the solution seemed to be callback functions. I tried this:

(function(callback) {
  let found = false;
  $.getJSON("people.json", function(data) {
    $.each(data.people, function() {
      if (this.number === $('#number').text()) {
        console.log("yes");
        found = true;
      }
    });
  });

  callback(found);
})(function(found) {
  if (found == false) {
    console.log("no");
  }
});

So I created these functions but it doesn't seem to be working as expected, as the callback function is executed before the other function ends.

When something is found, the console will log no and then yes, which means that it's not happening sequencially.

And now that I see that there is no synchronization on this function, how can I be sure that the rest of my js file is working as expected? When can you expect synchronization and when can you not?

Deleted the function and did this:

let found = false;
$.getJSON("people.json", function(data) {
  $.each(data.people, function() {
    if (this.number === $('#addFriendScreen > p').eq(0).text()) {
      found = true;
      console.log("true");
    }
  });
  if (found === false) {
    console.log("false");
  }
});

}

Now it works

  • You have to call the `callback` function inside the callback for the ajax call – adeneo May 16 '18 at 19:01
  • Sorry but I don't really know what ajax is, what does this mean? –  May 16 '18 at 19:03
  • `$.getJSON` is an ajax call, it's async, so it makes a call, and then calls the callback function when done. You can't return the result before the call has actually been made and completed, see the duplicate for a better explanation of how it works. – adeneo May 16 '18 at 20:37

0 Answers0