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