title: Promises and race-conditions
body: <p>I'm currently a little stuck with a race condition, and I'm pulling my hair out. Essentially, I'm querying an API, adding the results to the DB, then doing stuff with the returned/saved data. </p>
  
  <p>I'm less asking about this specific problem, and more the design pattern of how to fix this sort of issue. The line <code>p.push(formatter.createAccounts(account, id));</code> might run upto 1000 times, and might take 20 seconds or so.</p>
  
  <p>Any ideas on what I'm doing wrong will be super helpful</p>
  
  <p>Thanks,
  Ollie</p>
  
  <hr>
  
  <pre><code>// get all users
  Promise.all(updatedUsers)
  .then(() =&gt; {
    // create an array of promises
    const p = [];
  
    users.then((user) =&gt; {
      ...
      ids.forEach((id) =&gt; {
        const accounts = foo.getAccounts(id, true); // returns a promise
        accounts.then((account) =&gt; {
          // add the return data from here to the promise array at the bottom
          p.push(formatter.createAccounts(account, id));
        });
      });
    });
  
    // this would ideally be a promise array of the data from above - but instead it just evaluates to [] (what it was set to).
    Promise.all(p).then(() =&gt; {
      // do my stuff that relies on the data here
    })
  });
  </code></pre>