Don
Don

Reputation: 1

unable to get value from promise when returing

i have function that will get the sum of data on a specific period

  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}`))
})

but when i run it my result is[object promise]. Why is that?

Upvotes: 0

Views: 33

Answers (2)

null
null

Reputation: 1162

You are suppose to process records[0].sum in that call back function. If you really want to use like that then use below

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

Upvotes: 0

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

You need to wait until promise finished:

  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

Upvotes: 1

Related Questions