title: Promise Chain Stuck in a Loop
body: <p>I want to call a function that returns a promise twice, but when the function ends up calling itself forever, sometimes the outer one and sometimes the inner one. This is the problematic function where <code>retrieveDependency()</code> returns a Promise.</p>
  <pre><code>function renderDiffProject(projName, branchName, res, org=undefined){
     let newScan;
     let oldScan;
     retrieveDependency(projName, branchName, 1, org).then(result =&gt; { 
        newScan = result;
        console.log(&quot;inside retrieve deps&quot;);
        return retrieveDependency(projName, branchName, 2, org);
     })
     .then(result =&gt; {
        oldScan = result;
        console.log(&quot;successfully got dependencies&quot;)
        res.render('project', {projname: projName, branch: branchName, proj:JSON.stringify(newScan), oldproj:JSON.stringify(oldScan)})
     })
  }
  </code></pre>
  <p>And this is the code for <code>retrieveDependency()</code></p>
  <pre><code>function retrieveDependency(projname, branch, n, org=undefined){
     return new Promise(function(resolve, reject){
        depList = []
        if (org != undefined){
           var sql = &quot;SELECT (scanid) FROM foozie WHERE project = '&quot; + projname + &quot;' AND branch = '&quot; + branch + &quot;' AND org = '&quot; + org + &quot;' ORDER BY hist_id DESC LIMIT &quot; + (n-1) + &quot;,1&quot;; 
        } else {
           var sql = &quot;SELECT (scanid) FROM foozie WHERE project = '&quot; + projname + &quot;' AND branch = '&quot; + branch + &quot;' ORDER BY hist_id DESC LIMIT &quot; + (n-1) + &quot;,1&quot;;
        }
        return database.query(sql).then(result =&gt; {
           scan_id = result[0].scanid;
           var sql = &quot;SELECT * FROM branch_scan WHERE fossa_scan_id = '&quot; + scan_id + &quot;'&quot;;
           return database.query(sql);
        }) 
        .then(result =&gt; {
           var promiseList = [];
           for (r in result){
              dep_name_version = result[r].dep_name_version;
              promiseList.push(getDepWrapper(dep_name_version, depList));
           }
           Promise.all(promiseList).then(result =&gt; {
              console.log(&quot;pushed all the promises for number&quot;, n);
              resolve(result);
           })
         })
     })
  }
  </code></pre>
  <p>And <code>database.query</code> is defined as below:</p>
  <pre><code>class Database {
    constructor() {
        this.connection = mysql.createConnection({
          host: 'azure.com',
          user: 'admin-portal-mysql',
          password: '2341234#1',
          database: 'yatadb'
        });
    }
    query( sql, args ) {
        return new Promise( ( resolve, reject ) =&gt; {
            this.connection.query( sql, args, ( err, rows ) =&gt; {
                if ( err )
                    return reject( err );
                resolve( rows );
            } );
        } );
    }
  </code></pre>