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

683 views
Skip to first unread message

kimsia sim

unread,
Nov 28, 2012, 2:10:20 AM11/28/12
to q-con...@googlegroups.com
Answer given over at StackOverflow here

On Wednesday, November 28, 2012 12:48:45 PM UTC+8, kimsia sim wrote:

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?

Code Runner

unread,
Nov 30, 2012, 11:10:43 AM11/30/12
to q-con...@googlegroups.com
You're probably looking for something like this:

function traverseFiles() {
    var promises = [];

    for (var i=0, l=pages.length; i<l; i++) {
        promises.push(getSizeSettingsFromPage(pages[i], calculateRatio));
    }
    return Q.all(promises).then(function () { return checkWhenReady(); });
}


Q.all turns an array of promises into a promise for the whole, fulfilled array.
Let us know how that works for you.
Reply all
Reply to author
Forward
0 new messages