A
A
axblue2018-06-03 23:28:15
JavaScript
axblue, 2018-06-03 23:28:15

How to wait for an asynchronous function to complete?

Hello there is a code:

var isLoginIn = false;

ajcom.register('login', (hCtx, email, pass) => {

     User.findOne({
        where: {
          email: email
        }
      }).then(function(foundUser) {
        if (foundUser && foundUser.password === pass) {
          console.log("Авторизация прошла успешно!");
          isLoginIn = tru;
        }
        else {
          console.log("Неверные данные, проверьте ваш email и пароль!");
        }
      });
      return {authorized: isLoginIn};
});

The problem is that I need to return {authorized: isLoginIn};return the data after the request to the database, if the authorization is successful, then isLoginIn = true;the fact is that the return {authorized: isLoginIn};request does not wait, how are these situations solved?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-06-03
@leshikgo

ajcom.register('login', async (hCtx, email, pass) => {
  const foundUser = await User.findOne({ where: { email } });
  
  if (foundUser && foundUser.password === pass) {
    console.log("Авторизация прошла успешно!");
    isLoginIn = true;
  } else {
    console.log("Неверные данные, проверьте ваш email и пароль!");
  }
  return { authorized: isLoginIn };
});

O
Opanagushin, 2018-06-03
@Opanagushin

If you do not go into too much detail, then you can do this:

User.findOne({
        where: {
          email: email
        }
      }).then(function(foundUser) {
        if (foundUser && foundUser.password === pass) {
          console.log("Авторизация прошла успешно!");
          isLoginIn = tru;
        }
        else {
          console.log("Неверные данные, проверьте ваш email и пароль!");
        }
      }).then(function() { 
         return {authorized: isLoginIn};
      });

But you need to understand that the function is asynchronous and in any case you will have to wait for its execution. If promises look unclear, then look at async\await

P
profesor08, 2018-06-04
@profesor08

async, await will easily solve your problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question