title: Nested Promises in node.js and pg
body: <p>I am new to node and writing a small application. I haven't used a language as asynchronous as this on the server before and have myself in a bit of a pickle. I need to take a string, query a table for an id, then insert in a second table using the result, then return a string from the funtion two levels up. I have a custom <code>dao</code> I use for the db stuff. Here is the function where it all happens:</p>
  
  <pre><code>function generateToken(data, userId, client) {
      var random = Math.floor(Math.random() * 100001);
      var sha256 = crypto.createHmac("sha256", random );
      var token = sha256.update(data).digest("base64");
      var query = dao.select(
          'auth.apps', 
          {  
              name: client.name, 
              version: client.version, 
              subversion: client.subversion, 
              patch: client.patch    
          }
      ).done(
          function(result) {
              dao.insert(
                  'auth.tokens',  
                  { 
                      user_id:userId, 
                      app_id: result.rows[0].id, 
                      token:token         
                  } 
               ); 
               return "mmmm yellllo";
           }
      ); 
  
      var ret_val = await(query);
      console.log("Token return: " + ret_val);
  
      return ret_val;
  }
  </code></pre>
  
  <p>and here is the relevant part of my dao for select:</p>
  
  <pre><code>dbo.prototype.select = function(table, where, order_by) {
  
      var where_clause = this.construct_where(where);
      var sql = 'SELECT * FROM ' + table + ' WHERE ' + where_clause;
  
      if(order_by  !== undefined) {
          sql = sql + ' ORDER BY ' + order_by;
      };  
      var result = this.pool.query(sql);
  
      return result;
  };
  </code></pre>
  
  <p>and insert:</p>
  
  <pre><code>dbo.prototype.insert= function(table, values) {
      var key_list='', value_list = ''; 
  
      for( var k in values) 
      {   
          key_list = key_list + ', ' + k;
          value_list = value_list + ", '" + values[k] + "'";
      }   
  
      // chop off comma space
      key_list = key_list.substring(2);
      value_list = value_list.substring(2);
  
      var sql = 'INSERT INTO ' + table + '(' + key_list + ') VALUES(' + value_list + ') RETURNING id';
  
      var result = this.pool.query(sql).catch(function(error) {
          console.log("SQL:" + sql + " error:" + error);
      });
  
      return result;
  };
  </code></pre>
  
  <p>How do unwind the double promise. I want the <code>generateToken</code> function to return the <code>token</code> variable but only after the insert query has finished.</p>