Reputation: 85
Can promise to be returned like below? Does the catch block return a promise or a normal Error?
async function beforeProcessing(ctx) {
try {
let res = await validateList(ctx)
return new Promise((resolve, reject) => {
if (res && res.length > 0) {
const customErr = new Error(`missing for ${res} types`);
customErr.statusCode = 422;
reject(customErr);
}
else {
resolve();
}
})
} catch (error) {
return new Error(error);
}
}
Upvotes: 0
Views: 2487
Reputation: 1075427
Yes, but there's no reason to. async
functions always return promises. Just handle that logic inline, and throw customErr
to reject the function's promise:
async function beforeProcessing(ctx) {
let res;
try {
res = await validateList(ctx)
} catch (error) {
return new Error(error); // *** This is highly suspect
}
if (res && res.length > 0) {
const customErr = new Error(`missing for ${res} types`);
customErr.statusCode = 422;
throw customErr;
}
}
But as I mentioned in a comment above, returning an error object is highly suspect, it fulfills the promise with the error rather than rejecting the promise. Just let the error propagate to the caller (which will reject the async
function's promise):
async function beforeProcessing(ctx) {
let res = await validateList(ctx)
if (res && res.length > 0) {
const customErr = new Error(`missing for ${res} types`);
customErr.statusCode = 422;
throw customErr;
}
}
Also, that if
condition looks odd vs. the error message. The error message makes it look like the condition should be <= 0
, not > 0
, but of course I could be inferring incorrectly there.
Upvotes: 3