Catfish
Catfish

Reputation: 19284

Function which returns a promise not working as expected

I have this promise chain in my code and it works just fine. Document actually has a value and is not null

...
.then(() => {
  return db.document.findOne({
    where: {
      id: _document.get('id', req.transaction)
    },
    include: [{
      model: db.documentChildren,
      attributes: ['id', 'reference', 'uri', 'contentType', 'type', 'page']
    },
    {
      model: db.tag,
      attributes: ['id', 'key', 'value'], // We don't want meta columns
      through: { attributes: [] } // Exclude join table
    }],
    transaction: req.transaction
  })
})
.then(document => {
    console.log('document = ', document)
    ...

Now I want to abstract that query into a function so that it can be reused.

I would have thought this would work, but for some reason document is always null and when I run the generated query it does have a result.

Why is document null when abstracting this query into its own function?

function findOneDocumentQuery (db, id, transaction) {
  return db.document.findOne({
    where: {
      id: id
    },
    include: [{
      model: db.documentChildren,
      attributes: ['id', 'reference', 'uri', 'contentType', 'type', 'page']
    },
    {
      model: db.tag,
      attributes: ['id', 'key', 'value'], // We don't want meta columns
      through: { attributes: [] } // Exclude join table
    }],
    transaction: transaction
  })
}

...
.then(() => {
  return findOneDocumentQuery(db, _document.get('id', req.transaction))       
})
.then(document => {
  console.log('document = ', document)
...

Upvotes: 0

Views: 34

Answers (1)

0xnoob
0xnoob

Reputation: 1037

I think the bracket to findOneDocumentQuery is wrong, it should be:

return findOneDocumentQuery(db, _document.get('id'), req.transaction);

Upvotes: 2

Related Questions