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

Showing 1-3 of 3 messages
how to use q.js promises to work with multiple asynchronous operations KimSia Sim 11/27/12 8:48 PM

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?

Re: how to use q.js promises to work with multiple asynchronous operations KimSia Sim 11/27/12 11:10 PM
Answer given over at StackOverflow here
Re: how to use q.js promises to work with multiple asynchronous operations Code Runner 11/30/12 8:10 AM
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.