I have JavaScript code that looks like this (using Sequelize in Node):
if (require.main == module) {
(async () => {
const my_var = await MyModel.createWithChildren('name', ['one', 'two']);
console.log('before');
console.log(await my_var.getChildren());
console.log('after');
})();
}
MyModel
has a static method that looks like this:
static async createWithChildren(name, children) {
const me = await Me.create({name: name});
const child_recs = await Child.bulkCreate(children.map((child) => ({child: child})));
child_recs.forEach(async (rec) => {
await rec.setParent(me);
await rec.save();
});
return me;
}
But when I execute this code, where every call to the Sequelize API is preceded by an await
, I get the "after" log before the last child update:
before
Executing (default): SELECT `id` ... FROM `children` WHERE `parent_id` = 1;
Executing (default): UPDATE `children` SET `parent_id`=? ...
[]
after
Executing (default): UPDATE `children` SET `parent_id`=? ...
The SELECT
is coming from, I think, the call the my_var.getChildren()
but is logging after "before," and the empty list is because it didn't "await" for the my_var.getChildren()
call? If everything were awaiting as I expect, the log would look something like this:
before
Executing (default): UPDATE `children` SET `parent_id`=? ...
Executing (default): UPDATE `children` SET `parent_id`=? ...
Executing (default): SELECT `id` ... FROM `children` WHERE `parent_id` = 1;
['one', 'two']
after
So if I'm "awaiting" every call, why am I not seeing that?