首页 > 解决方案 > 在 Sequelize 中将 then promise 用于链式 promise 时未定义对象

问题描述

我正在使用以下代码对invoiceSequelize 中的对象使用链式承诺。但是对于 .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. 我在这里做错了什么?

标签: javascriptnode.jspromisesequelize.js

解决方案


那是因为您需要在第一个.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.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(...)

推荐阅读