title: Using node.js and promise to fetch paginated data
body: <p>Please keep in mind that I am new to node.js and I am used with android development.</p>
  
  <p>My scenario is like this: </p>
  
  <ol>
  <li>Run a query against the database that returns either null or a value</li>
  <li>Call a web service with that database value, that offers info paginated, meaning that on a call I get a parameter to pass for the next call if there is more info to fetch.</li>
  <li>After all the items are retrieved, store them in a database table</li>
  <li>If everything is well, for each item received previously, I need to make another web call and store the retrieved info in another table</li>
  <li>if fetching any of the data set fails, all data must be reverted from the database</li>
  </ol>
  
  <p>So far, I've tried this:</p>
  
  <pre><code>getAllData: function(){
    self.getMainWebData(null)
       .then(function(result){
         //get secondary data for each result row and insert it into database
     }
  }
  
  
  getMainWebData: function(nextPage){
      return new Promise(function(resolve, reject) {
  
        module.getWebData(nextPage, function(errorReturned, response, values) {
  
      if (errorReturned) {
            reject(errorReturned);
          }
  
          nextPage = response.nextPageValue;
          resolve(values);
        })
      }).then(function(result) {
  
      //here I need to insert the returned values in database     
  
        //there's a new page, so fetch the next set of data
        if (nextPage) {
            //call again getMainWebData? 
            self.getMainWebData(nextPage)
        }
  
      })
  </code></pre>
  
  <p>There are a few things missing, from what I've tested, getAllData.then fires only one for the first set of items and not for others, so clearly handling the returned data in not right.</p>
  
  <p>LATER EDIT: I've edited the scenario. Given some more research my feeling is that I could use a chain or <code>.then()</code> to perform the operations in a sequence.</p>