diff --git a/lib/plugins/saveSubdocs.js b/lib/plugins/saveSubdocs.js index 52ea5a82e26..4b47bd73320 100644 --- a/lib/plugins/saveSubdocs.js +++ b/lib/plugins/saveSubdocs.js @@ -58,9 +58,8 @@ 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; } @@ -68,21 +67,32 @@ module.exports = function saveSubdocs(schema) { 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); };