Note: This question is also cross-posted in StackOverflow over here.
########################################################################################
I had a situation with multiple asynchronous operations and the answer I accepted in StackOverflow pointed out that using Promises using a library such as q.js would be more beneficial.
I am convinced to refactor my code to use Promises but because the code is pretty long, i have trimmed the irrelevant portions and exported the crucial parts into a separate repo.
The repo is here and the most important file is this.
The requirement is that I want pageSizes to be non-empty after traversing all the dragged'n dropped files.
The problem is that the FileAPI operations inside getSizeSettingsFromPage function causesgetSizeSettingsFromPage to be async.
So I cannot place checkWhenReady(); like this.
function traverseFiles() { for (var i=0, l=pages.length; i<l; i++) { getSizeSettingsFromPage(pages[i], calculateRatio); } checkWhenReady(); // this always returns 0. }
This works, but it is not ideal. I prefer to call checkWhenReady just ONCE after all the
pages
have undergone this function calculateRatio successfully.function calculateRatio(width, height, filename) { // .... code pageSizes.add(filename, object); checkWhenReady(); // this works but it is not ideal. I prefer to call this method AFTER all the `pages` have undergone calculateRatio // ..... more code... }
How do I refactor the code to make use of Promises in Q.js?