简体   繁体   English

在Promise链Node.js中传递数据

[英]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. 我有一个承诺,第一个承诺从API获取数据,第二个承诺将数据插入数据库。

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: 您总是reject兑现承诺:

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 . 这会导致触发.catch回调( .catch((err) => { console.log('error'); }) ),该balanceArray不返回任何内容,因此balanceArrayundefined

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: 其次,可以将错误重新抛出.catch回调中,或者将其完全删除并在顶级捕获:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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