0

I'm using the following code to use chained promise for invoice object in Sequelize. But invoice object is undefined for the second usage of then.

Invoice.create({
    //set values for invoice object
}).then(invoice => { //update company id
    //invoice belongs to a company
    Company.findOne({where: {id: companyId}}).then(company => {
        return invoice.setCompany(company)
    })
}).then(invoice => {
    console.log('Invoice is: ' + invoice)
    //create child items
    invoice.createItem({
        //set item values
    })
}).catch(err => {
    console.log('Invoice create error: ' + err)
})

The output in the console is Invoice is :undefined. What I have done wrongly here?

Indika Rajapaksha
  • 1,056
  • 1
  • 14
  • 36
  • Are you trying to chain the promise response or branch it out? Have a look at this response https://stackoverflow.com/questions/32216619/is-there-a-difference-between-promise-then-then-vs-promise-then-promise-then/32216660#32216660 – Surya May 07 '20 at 07:18

1 Answers1

2

That's because you need to return the promise in your first .then callback.

Change this:

Invoice.create({
    //set values for invoice object
}).then(invoice => { //update company id
    //invoice belongs to a company
    Company.findOne({where: {id: companyId}}).then(company => {
        return invoice.setCompany(company)
    })
}).then(...)

To:

Invoice.create({
    //set values for invoice object
}).then(invoice => { 
    // return this promise
    return Company.findOne({where: {id: companyId}}).then(company => {
        invoice.setCompany(company)
        // you also need to return your invoice object here
        return invoice
    })
}).then(...)
ethane
  • 2,329
  • 3
  • 22
  • 33