I'm trying to check the results of "checkWorkflow" but it seems to be running the "If" statement before checking, i think this because of my console output. I feel like i'm doing something wrong with the promise, but i'm kinda at a lost at this point.
Console Output
Promise { pending } *When i console.log(doesWorkflowExists)
workflow already exists, please rename
error2
const createWorkflow = async (req, res) => {
try {
const doesWorkflowExists = checkWorkflow(req.name);
if (!doesWorkflowExists) {
console.log('do stuff')
}
else {
console.log('workflow already exists, please rename')
}
} catch (error) {
handleError(res, error);
console.log("error on create workflow");
}
};
vvvv checkWorkflow vvvv
const checkWorkflow = (name = '') => {
return new Promise((resolve, reject) => {
Workflow.findOne(
{
name,
},
(err, item) => {
if (err) {
console.log('error1')
return reject(buildErrObject(422, err.message));
}
if (item) {
console.log('error2')
return reject(buildErrObject(404, "WORKFLOW_ALREADY_EXISTS"));
}
resolve();
}
);
});
};
In your
checkWorkflow
function, you return a Promise. When you callcheckWorkflow
function like this :doesWorkflowExists
is a pending Promise. On the console, you can see that.You need to "wait" until the Promise
resolve
the result orreject
the error. Just add "await" keyword before the function call, like this:The rest seems to be fine, it should work :)