75
76// Update client
77ClientSchema.statics.update = (clientId, client, company) => {
78 return new Promise(async (resolve, reject) => { 79 if (company) {
80 var Company = mongoose.model('Company');
81 var query = Company.findOneAndUpdate(
36
37// Create client
38ClientSchema.statics.create = (client, company) => {
39 return new Promise(async (resolve, reject) => { 40 if (company) {
41 var Company = mongoose.model('Company');
42 var query = Company.findOneAndUpdate(
1166
1167// Delete audit parent
1168AuditSchema.statics.deleteParent = (isAdmin, auditId, userId) => {
1169 return new Promise(async (resolve, reject) => {1170 var query = Audit.findByIdAndUpdate(auditId, { parentId: null });
1171 if (!isAdmin) query.or([{ creator: userId }, { collaborators: userId }]);
1172 query
1144
1145// Update audit parent
1146AuditSchema.statics.updateParent = (isAdmin, auditId, userId, parentId) => {
1147 return new Promise(async (resolve, reject) => {1148 var query = Audit.findByIdAndUpdate(auditId, { parentId: parentId });
1149 if (!isAdmin) query.or([{ creator: userId }, { collaborators: userId }]);
1150 query
1111 });
1112
1113AuditSchema.statics.updateApprovals = (isAdmin, auditId, userId, update) => {
1114 return new Promise(async (resolve, reject) => {1115 var Settings = mongoose.model('Settings');
1116 var settings = await Settings.getAll();
1117
The new Promise
constructor accepts an executor
function as an argument, which has resolve
and reject
parameters that can be used to control the state of the created Promise.
For example:
const result = new Promise(function executor(resolve, reject) {
readFile('foo.txt', (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
The executor function can also be an async function
.
However, this is usually a mistake, for a few reasons:
Promise
constructor can only catch synchronous exceptions, and an async function never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.Promise
to reject. This could make it difficult to debug and handle some errors.await
, this is usually a sign that it is not actually necessary to use the new Promise constructor, or the scope of the new Promise
constructor can be reduced.const foo = new Promise(async (resolve, reject) => {
readFile('foo.txt', (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = new Promise(async (resolve, reject) => {
resolve(await foo);
});
const foo = new Promise((resolve, reject) => {
readFile('foo.txt', function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
const result = Promise.resolve(foo);