Promise not resolving before IF STATEMENT

91 Views Asked by At

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();
      }
    );
  });
};
1

There are 1 best solutions below

0
On BEST ANSWER

In your checkWorkflow function, you return a Promise. When you call checkWorkflow function like this :

const doesWorkflowExists = checkWorkflow(req.name);

doesWorkflowExists is a pending Promise. On the console, you can see that.

You need to "wait" until the Promise resolve the result or reject the error. Just add "await" keyword before the function call, like this:

const doesWorkflowExists = await checkWorkflow(req.name);

The rest seems to be fine, it should work :)