Search code examples
node.jsloopback

How to stop promise to further execute after return and next function call back?


I am checking for user id in loopmodal and then checking if the email is already existing but have to stop the promise from further proceeding if the condition is satisfied and exit form it. I am returning next function in then but my code continues to execute. Following is my code

User.findOne<UserPersistedModel<UserModel> & UserModel>({
      where: {email: email},
    })
    .then(user => {
    if (user) {
      error = new Error(g.f('This {{email}} is already in use.'));
      (error as HttpError).statusCode = 400;
      (error as HttpError).code = 'EMAIL_NOT_VALID';
      next(error);
      return;
    }}).then(user => console.log('Why getting here')).catch((err?: HttpError) => err && next(err));

Solution

  • There's only really two ways to stop this:

    • throw inside the then which skips the next one but will run the catch
    • Return something and then use it to verify whether you want to run the code inside the next then

    I think in your case, it looks like it would just make sense to throw the error you create and then let the catch propagate it e.g.

    .then(user => {
      if (user) {
        const error = new Error(g.f('This {{email}} is already in use.'));
        (error as HttpError).statusCode = 400;
        (error as HttpError).code = 'EMAIL_NOT_VALID';
        throw error;
      }
    })
    .then(user => { ... }) // this part would skip
    .catch(next) // you don't need to check if an error exists in `catch`, it will always exist