-1

I am developing nodejs API. In some of my APIs, i need to check whether some of the parameters are unique or not in database and i need to code it in a separated method to share the function. (PS: I don't want to do it in sequelize models)

My api call like this

    var duplicate = checkUniqueEmail(req.body.email);
    console.log(duplicate);
    if(duplicate == true){ 
       //do something 
    } else { 
       //return error 
    };

The checking method like this

  function checkUniqueEmail(email){
    db.users.find( {
        where: {email: email} 
    }).then( (result) => {
        if(result !== null){
           return false;
        } else {
           return true;
        }
    }).catch(err => {
         console.log(err);
    });

  }

But finally i got undefined by console.log(duplicate)

The problem seems that i log the result before it executing and return some results,it should be a javascript async problem.

How can i modify my code to achieve my target?

KEN IP
  • 72
  • 1
  • 7
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Jul 05 '19 at 08:16

1 Answers1

0

The problem with your code is that checkUniqueEmail function doesn't return any value. You either have to rewrite it using async and await, or add return keyword before the call to the DB:

async foo() {
   var duplicate = await checkUniqueEmail(req.body.email);
   console.log(duplicate);
   if (duplicate == true){ 
      //do something 
   } else { 
      //return error 
   }
}

async checkUniqueEmail(email){
   try {
      var result = await db.users.find({where: {email: email}});
      if (result !== null){
         return false;
      } else {
         return true;
      }
   } catch (err) {
      console.log(err);
   }
}
Anna Tolochko
  • 1,795
  • 14
  • 20