jdotdoe
jdotdoe

Reputation: 507

Promises.js - am I doing it right?

My code

//run this first
 var promises = TransactionDetails.findAll({
      where: {
          //transaction_pincode:randomNumber,
          merchant_id:req.session.userId,
          transaction_verified:1
      } 
    }).then(transactionDetails => {
        var results = transactionDetails;
    }).catch(function(error){
      res.status(500);
      console.log(error);
      //res.json({error:error, stackError:error.stack});
      console.log("Error at dashboard:" + error);
      var results = "Error.";
    });

//then only run this
    Promise.all(promises).then(function(){
      res.render('dashboard',{data:results});
      console.log(data);
    });

I would like to run the first block of code before running the code inside Promise.all. The issue here is that the code inside Promise.all gets executed first before the code in var promises finish running. How can I fix this ?

Upvotes: 0

Views: 54

Answers (1)

Tom Davies
Tom Davies

Reputation: 899

Promise.all is useful when you want to wait for multiple promises to finish. In this case it looks like you're just waiting for a single one.

In which case it makes more sense to just move your processing into the .then(), like this:

TransactionDetails.findAll({
  where: { /*query*/ } 
}).then(transactionDetails => {
    res.render('dashboard',{data: transactionDetails});
    console.log(transactionDetails);
}).catch(function(error){ /*error handling*/ });

The normal flow of your code won't wait for a promise to finish, so anything that relies on the result of the promise should be inside of .then().

There are some newer language features in ES7 (async/await) that make this a bit nicer to reason about, so you could look up that if you're interested.

Upvotes: 1

Related Questions