重做时无法从承诺中获得价值

时间:2018-09-03 17:44:27

标签: javascript promise

我具有可以在特定时间段内获取数据总和的功能

  const cashData = db.query(`SELECT SUM (payments_log.amount_paid) FROM payments_log WHERE payments_log.payment_method = '2' AND payments_log.inserted_at BETWEEN $1 AND NOW() `, [date])
.then(records => {
  return records[0].sum
})
.catch(error => {
  cb(new Error(`Print failed: ${error}`))
})

但是当我运行它时,我的结果是[对象承诺]。这是为什么?

2 个答案:

答案 0 :(得分:1)

您需要等到诺言完成:

  const cashData = db.query(`SELECT SUM (payments_log.amount_paid) FROM payments_log WHERE payments_log.payment_method = '2' AND  payments_log.inserted_at BETWEEN $1 AND NOW() `, [date])
   .then(records => {
     return records[0].sum
 })
  .catch(error => {
    cb(new Error(`Print failed: ${error}`))
 });

 cashData.then(res => console.log(res));

Promise Docs

答案 1 :(得分:0)

您应该在该回调函数中处理records[0].sum。如果您真的想这样使用,请在下面

.then(records => { return records[0].sum })
.then(res => { // your sum here })
.catch(error => { cb(new Error(Print failed: ${error})) })
相关问题