简体   繁体   中英

Object not defined when using then promise for chained promises in Sequelize

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?

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(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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