You'll want to put that stuff in the else
branch inside that callback:
function addUser(request) {
return new Promise((res, rej) => {
ValidateFormData(request, CREATE_USER, (err) => {
if (err) {
rej(makeError(err));
} else {
console.log('creating user');
res();
}
});
});
}
Putting it outside of the asynchronous callback (regardless whether outside of ValidateFormData
, or even outside new Promise
) will cause it to run immediately, and you won't have a chance to prevent it retroactively when the error has occurred in the future.
Alternatively, use a then
callback to process the result, if there's more than a simple log() that cannot fail:
function addUser(request) {
return new Promise((res, rej) => {
ValidateFormData(request, CREATE_USER, (err) => {
if (err) rej(makeError(err));
else res();
});
}).then(() => {
console.log('creating user');
…
});
}
This is especially useuful as it allows to just util.promisify
your ValidateFormData
function.