Multiple Asynchronous Callbacks Javascript How Do I Resolve This?
I got myself into a tangle which probably involves multiple asynchronous callback situations. I have a javascript function called populatePageArea() Inside populatePageArea it trav
Solution 1:
The simple solution (I have marked my changes with // ***
:
// ***var totalPages;
functionpopulatePagesArea() {
// there was some code before the for loop// ***
totalPages = pages.length;
for (var i=0, l=pages.length; i<l; i++) {
addToPagesArea(pages[i], "");
}
// some code after...
}
functionaddToPages(file, front) {
// there was some code before..
reader = newFileReader();
reader.onload = (function (theDiv) {
returnfunction (evt) {
var backgroundimage = "url(" + evt.target.result + ")";
theDiv.css("background-image", backgroundimage);
var sizeSettings = getSizeSettingsFromPage(file, calculateRatio);
// *** Check to see if we're done after every loadcheckPagesReady();
};
}(imageDiv));
// step#3 execute file reader
reader.readAsDataURL(file);
// there was some code after..
}
// *** Call getMajorityPageSize() here, only after all pages have loaded.functioncheckPagesReady() {
if (pageSizes.length >= totalPages)
getMajorityPageSize();
}
The better solution if you're going to be dealing with more asynchronous things later on would be to refactor your code using promises. Promises is an API designed for dealing with asynchronous programming in a systematic and organized way. It'll make your life a lot easier if you're going to be doing more async work. There's a lot of free libraries that support promises, one of the major players is Q.js.
Post a Comment for "Multiple Asynchronous Callbacks Javascript How Do I Resolve This?"