我需要从promise中排除变量的值,但是我不能,因为它的范围。就我而言,我正在使用Sequelize将数据保存到SQL数据库中,但我想使用类和dataToReturn
在第二个save
之后收到的承诺
.post('/', (req, res) => {
const event = new Event(Events, Data, req.body)
event.save()
res.status(201).json("HERE I NEED THE 'dataToReturn' from the promise")
})
这是我的课堂活动
class Event {
constructor(Events, Data, Event) {
this._Data = Data,
this._Events = Events
this._Event = Event
}
save() {
this._Data.build(this._Event.Data).save().then((res) =>
this._Events.build({
name: this._Event.name,
date: this._Evento.fecha,
photo1: this._Event.photo1,
photo2: this._Event.photo2,
idData: res.dataValues.id
}).save().then((dataToReturn) => "???")) <-- dont know what to do here
return dataToReturn <-- I want to return that variable but I cant because scopes
}
你有什么建议吗?
我迷路了
最佳答案
class Event {
/**
* Same code
*/
save() {
return this._Data.build(this._Event.Data).save().then((res) =>
this._Events.build({
name: this._Event.name,
date: this._Evento.fecha,
photo1: this._Event.photo1,
photo2: this._Event.photo2,
idData: res.dataValues.id
})).save();
}
然后在您的路线中使用
then
:.post('/', (req, res) => {
const event = new Event(Events, Data, req.body)
event.save().then((dataToReturn) => {
res.status(201).json(dataToReturn);
});
})