Reputation: 2356
I'm trying to store Sequelizes instance.save
method in a variable to be called later. When I call it from that variable it throws error Unhandled rejection TypeError: Cannot read property 'isNewRecord' of undefined.
Save is performed on an associated object in array loaded thorough eager loading. If I call directly the code I'm trying to store, it works. It fails just when stored.
My code:
models.Person.hasMany(models.TaskExecutor, { foreignKey: 'personID' });
models.TaskExecutor.belongsTo(models.Person, { foreignKey: 'personID' });
const options = {
include: [
{
model: models.TaskExecutor,
where: { ... }
}
]
};
let handler;
models.Person.findOne(options)
.then(person => {
handler = person.task_executors[0].save;
handler().then(...); // THIS THROWS ERROR
// HOWEVER
person.task_executors[0].save().then(...); // WORKS JUST FINE
})
Any idea what might be the cause for this?
Upvotes: 0
Views: 81
Reputation: 46
You probably need to bind the this
keyword variable when creating the handler because the save method is a class method. You can do it like this:
const handler = person.task_executors[0].save.bind(person.task_executors[0]);
handler.then() ....
You can read more about this
here https://medium.com/quick-code/understanding-the-this-keyword-in-javascript-cb76d4c7c5e8
Upvotes: 1