Wednesday, 24 May 2017

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?



via chuckieDub

No comments:

Post a Comment