Search code examples
redispromisees6-promisenode-redis

Why aren't my promises resolving while using node and redis? My array returns the first iteration instead of waiting for the entire code to run


app.get('/lists/get_emails', function(req, res) {
  //  Return *all* the emails that appear in *any* of the lists in
  // `req.body.lists`. Emails should only appear once.
  let queryArr = req.query.lists.split(",");
  var retArr = [];
  Promise.all(queryArr.map(list => {
    redisClient.smembersAsync(list)
      .then((results) => {
        if(results) {
          console.log('retArr  before push', retArr);
          for (email in results) {
            retArr.push(results[email])
          }
          console.log('retArr after push', retArr);
          return Promise.all(retArr);
        } else {
          res.send({results: null});
        }
      })
      .then(result => {
        console.log('resssssss!', result);
        return Promise.all(result);
      })
      .catch(error => {
        console.log('error submitting final emails', error);
      });
  }))
})

When retArr is returned it contains the emails for one list, but not all of them. My console logs show that the lists are loaded into retArr, but it seems that retArr is returning before all of the emails are pushed. why?


Solution

  • Your redisClient.. chain returns a promise, but you arent returning that promise to the map.

    return redisClient(... should fix it.