Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to use q.js promises to work with multiple asynchronous operations
    text
    copied!<p>Note: This question is also cross-posted in Q.js mailing list over <a href="https://groups.google.com/forum/#!topic/q-continuum/nY0R3010GM4" rel="nofollow noreferrer">here</a>.</p> <hr> <p>i had a situation with multiple asynchronous operations and the <a href="https://stackoverflow.com/a/13585086/80353">answer I accepted</a> pointed out that using Promises using a library such as q.js would be more beneficial.</p> <p>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.</p> <p>The repo is <a href="https://github.com/simkimsia/learn-promises-javascript" rel="nofollow noreferrer">here</a> and the most important file is <a href="https://github.com/simkimsia/learn-promises-javascript/blob/master/testqjs.html" rel="nofollow noreferrer">this</a>.</p> <p>The requirement is that I want <strong>pageSizes</strong> to be non-empty after traversing all the dragged'n dropped files.</p> <p>The problem is that the FileAPI operations inside <strong>getSizeSettingsFromPage</strong> function causes <strong>getSizeSettingsFromPage</strong> to be async.</p> <p>So I cannot place <strong>checkWhenReady();</strong> like this.</p> <pre><code>function traverseFiles() { for (var i=0, l=pages.length; i&lt;l; i++) { getSizeSettingsFromPage(pages[i], calculateRatio); } checkWhenReady(); // this always returns 0. } </code></pre> <p>This works, but it is not ideal. I prefer to call checkWhenReady just ONCE after all the <code>pages</code> have undergone this function calculateRatio successfully.</p> <pre><code>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... } </code></pre> <p><strong>How do I refactor the code to make use of Promises in Q.js?</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload