How Can I Write An Async Method In Javascript When Posting Or Looping?
I have made a loop in my JavaScript code and in that loop I use an XMLHttpRequest with a callback method but I'm having a problem with it. When my loop ends the callback executes.
Solution 1:
You basically have to change your thinking. You need to change your style from writing code like this:
for (var i = 0; i < stuff.length; i++) {
var exist = IsstuffExist(stuff[i]);
alert(exist);
}
to writing stuff like this:
for (var i = 0; i < stuff.length; i++) {
IsstuffExist(stuff[i], function(exist) {
alert(exist);
});
}
the IsstuffExist
function can be written like this:
function IsstuffExist (stuff, callback) {
// Do things and once you get the `exist` variable you can// pass it to the callback function. Any code that needs// to continue processing things can then resume from// within the callback function:callback(exist);
}
This technique can be nested, passing the callback function to other callback functions. A concrete example is with ajax calls:
// I'm using my own ajax library in this example but it's the same// if you use other libraries:functionIsstuffExist (stuff, mycallback) {
// Make ajax call to find out if stuff exist:
ajax('some/url.com', {
callback : function (r) {
var status = r.responseText;
mycallback(status);
}
});
}
note: I renamed the callback for the function to mycallback
to avoid confusion. But in real code I would simply name it callback
.
So now instead of writing code like this:
for (var i = 0; i < stuff.length; i++) {
if(IsstuffExist(stuff[i])) {
doSomethingAndUpdateTheHTML();
}
}
you write it like this:
for (var i = 0; i < stuff.length; i++) {
IsstuffExist(stuff[i],function(exist){
if (exist) {
doSomethingAndUpdateTheHTML();
}
});
}
Post a Comment for "How Can I Write An Async Method In Javascript When Posting Or Looping?"