TechnoCorner TechnoCorner - 3 months ago 14
Javascript Question

Issue with waiting for an event to be done then execute another

I'm trying to use jQuery Promises to solve a problem.

I have a UI in which I make an API call and waiting for a response (Which takes a while). I want to wait for the response to see if everything is loaded then do an action. How can I achieve this?

This is my code:

var d1 = new $.Deferred();

if(($('.fa-spin').length + $('.chart-loading').length )==0){
d1.resolve();
} //Logic behind here is, I'm checking for loading icon,
loading spinner and once they are destroyed,
I want to execute something!

$.when(d1).then(function() {
console.log("fetched");
//Run something
});


I want to check if my loading spinner is done, and then fire an event. How can I do this?

When I execute this code, the deferred never gets resolved and fetch is never printed

Answer

you'll need to continually check in order to resolve:

var d1 = new $.Deferred();

var testInterval = setInterval(function() {
  if(($('.fa-spin').length + $('.chart-loading').length )==0){
    clearInterval(testInterval);
    d1.resolve();
  }
},100);

$.when(d1).then(function() {
    console.log("fetched");
    //Run something
});

this will check every .1sec if the spinner's gone, and resolve your defer object when the condition is met. although, you could just run your code there instead of as a defer/resolve.

additionally it might be more effective to hook into your actual process rather than the existence of a spinner dom object, consider implementing an existing observer pattern or roll your own: observer pattern