chuckieDub
chuckieDub

Reputation: 1835

Passing data in promise chain nodejs

I have a chain of promises that the first one gets data from an API, and the 2nd one inserts the data into a database.

I am attempting to pass the data from the first promise to the 2nd promise, but it's coming through as undefined.

Here is my code:

var getBalancePromise = function() {
  var promise = new Promise(function(resolve, reject) {
    poloniexExchange.getBalance({
      account: 'all'
    }, function(err, response) {
      if (err)
        console.log(err);
      reject(err);
      if (!err)
        resolve(response); //response is an array
    });
  }).catch((err) => {
    console.log('error');
  })
  return promise;

};

var updateBalancePromise = function(balanceArray) //balanceArray undefined. This should be the data from the first promise in the chain.
{
  var promise = new Promise(function(resolve, reject) {
    balanceArray.data.forEach(function(element) {
      db.collection('balances').update({
        currency: element.currency
      }, {
        $set: {
          amount: element.amount,
          shortname: element.shortName
        }
      }, {
        upsert: true
      });
    });
    resolve(true);
    console.log('balances updated into database');
  });
  return promise;
};

getBalancePromise()
  .then(updateBalancePromise);

How do I change my code to pass data from first promise to 2nd promise?

Upvotes: 0

Views: 711

Answers (1)

Felix Kling
Felix Kling

Reputation: 816404

You are always rejecting the promise:

if (err)
  console.log(err);
reject(err); // This line is always executed
if (!err)
  resolve(response); //response is an array

This causes the .catch callback to be triggered (.catch((err) => { console.log('error'); })) which doesn't return anything, so balanceArray is undefined.

First make sure to only reject the promise if there is an error:

if (err) {
  console.log(err);
  reject(err);
}

Secondly, either rethrow the error in the .catch callback or remove it completely and catch at the top level instead:

getBalancePromise()
  .then(updateBalancePromise)
  .catch(...);

Upvotes: 5

Related Questions