CanKer DiAlike CanKer DiAlike - 6 months ago 15
Javascript Question

Return a promise variable ouside the promise

I need to get outside from the promise the value of a variable but I can't because the scope of that. In my case i'm using Sequelize to save data to a SQL database but I wanna do with classes and the

dataToReturn
I receive with the promise after second
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")
})


and this is my Class Event

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
}


What do you recommend?
I'm lost

Answer
   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 use thenin your route:

.post('/', (req, res) =>  {
  const event = new Event(Events, Data, req.body)
  event.save().then((dataToReturn) => {
   res.status(201).json(dataToReturn);
  });
})
Comments