how to use q.js promises to work with multiple asynchronous operations

Posted by kimsia on Stack Overflow See other posts from Stack Overflow or by kimsia
Published on 2012-11-28T04:37:12Z Indexed on 2012/11/28 5:04 UTC
Read the original article Hit count: 146

Note: This question is also cross-posted in Q.js mailing list over here.


i had a situation with multiple asynchronous operations and the answer I accepted 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 causes getSizeSettingsFromPage 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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about asynchronous