简体   繁体   中英

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?

You are always reject ing 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(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM