Search code examples
javascriptnode.jspromisees6-promise

Promises and race-conditions


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.

I'm less asking about this specific problem, and more the design pattern of how to fix this sort of issue. The line p.push(formatter.createAccounts(account, id)); might run upto 1000 times, and might take 20 seconds or so.

Any ideas on what I'm doing wrong will be super helpful

Thanks, Ollie


// get all users
Promise.all(updatedUsers)
.then(() => {
  // create an array of promises
  const p = [];

  users.then((user) => {
    ...
    ids.forEach((id) => {
      const accounts = foo.getAccounts(id, true); // returns a promise
      accounts.then((account) => {
        // 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(() => {
    // do my stuff that relies on the data here
  })
});

Solution

  • The problem is that you are not including the foo.getAccounts promise into your promises array. Modified version:

    Promise.all(updatedUsers)
    .then(() => {
    
      users.then((user) => {
        return Promise.all(ids.map(id => {
          //for each ID we return a promise
          return foo.getAccounts(id, true).then(account => {
            //keep returning a promise
            return formatter.createAccounts(account, id)
          })
    
        }).then((results) => {
          //results is an array of the resolved values from formatter.createAccounts
          // do my stuff that relies on the data here
        })
      })
    
     //rest of closing brackets