Question

I have two functions, lets call them functionA and functionB

Inside each of these functions are XHR calls to download files, if I call the functions as follows

functionA();
functionB();

They will both execute, however functionB can many times finish before functionA (due to the large size of a file being downloaded with functionA. But this breaks the functioning of my app, and I would prefer to have functionB only fire after functionA has completly finished downloading its data.

Now the obvious answer to me at first is to simply place the call to functionB inside the XHR call of functionA, but I cant do it that way because of the way my code is setup (commonJS sutff...)

Is there a way to basicly force functionA to finish itself and return before functionB will start?

Était-ce utile?

La solution

You can use callbacks, here is an example. It basically passes functionB to functionA and then calls functionB at the end of functionA

var functionA = function(cb) {
    //do some stuff
    cb();
};
var functionB = function() {
    //do some stuff
};
functionA(functionB);

Also, if you google javascript callbacks, you'll find many different articles on them. Enough to keep you busy reading for quite awhile.

Autres conseils

you can also look in to libraries like async.js.

these libraries introduce the concept of promises into you code and reduce the chaos of all of the async callbacks.

https://github.com/caolan/async#readme

http://www.html5rocks.com/en/tutorials/async/deferred/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top