Объект не определен при использовании затем обещания для связанных обещаний в Sequelize - PullRequest
0 голосов
/ 07 мая 2020

Я использую следующий код для использования связанного обещания для объекта invoice в Sequelize. Но объект invoice не определен для второго использования 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)
})

Вывод в консоли Invoice is :undefined. Что я здесь сделал неправильно?

1 Ответ

2 голосов
/ 07 мая 2020

Это потому, что вам нужно вернуть обещание в своем первом .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(...)

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