Skip to content

Commit

Permalink
refactor: use async/await for subdoc post save
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Jul 7, 2024
1 parent 5f55a30 commit 50f1a73
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions lib/plugins/saveSubdocs.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,31 +58,41 @@ module.exports = function saveSubdocs(schema) {
await Promise.all(promises);
});

schema.s.hooks.post('save', function saveSubdocsPostSave(doc, next) {
schema.s.hooks.post('save', async function saveSubdocsPostSave() {
if (this.$isSubdocument) {
next();
return;
}

const _this = this;
const subdocs = this.$getAllSubdocs();

if (!subdocs.length) {
next();
return;
}

each(subdocs, function(subdoc, cb) {
subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) {
cb(err);
});
}, function(error) {
if (error) {
return _this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
next(error);
const promises = [];
for (const subdoc of subdocs) {
promises.push(new Promise((resolve, reject) => {
subdoc.$__schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) {
if (err) {
return reject(err);
}
resolve();
});
}
next();
});
}));
}

try {
await Promise.all(promises);
} catch (error) {
await new Promise((resolve, reject) => {
this.$__schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) {
if (error) {
return reject(error);
}
resolve();
});
});
}
}, null, unshift);
};

0 comments on commit 50f1a73

Please sign in to comment.