Unable to keep promise

I have no idea why I cannot hide the promise correctly, here is my code

app.post('/login', urlencodedParser, async (req, res) => {
  // authenticate is async function that return promise
  model.authenticate(req.body.uname, req.body.pword)
    .then(function (result) {
      console.log(result);
      // ... some codes
    });
});

// here is the function authenticate
async function authenticate(uname, pword) {
  User.find({username: uname}, 'password', function (err, result) {
    if (err !== null){
      return new Promise(function (resolve, reject) {
        resolve(false);
      });
    }
    else{
      if (pword === result[0].password){
        console.log("Correct Password!");
        return new Promise(function (resolve, reject) {
            resolve(true);
        });
      }

But the output is in my console

undefined
Correct Password!

which indicate that .then () is implemented before authentication is complete. So how can I code it better? many thanks!

+4
source share
3 answers

The problem is that the body of your authentication function does not return anything. It calls an asynchronous function that uses a callback, and then returns an implicit promise to allow undefined.

async function authenticate(uname, pword) {
  User.find({username: uname}, 'password', function (err, result) {
    // This will run sometime after authenticate returns
  });
}

You need to wrap the challenge User.findin a promise.

// here is the function authenticate
async function authenticate(uname, pword) {
  return new Promise(function (resolve, reject) () {
    User.find({username: uname}, 'password', function (err, result) {
      if (err !== null){
        resolve(false);
      }
      else{
        if (pword === result[0].password){
          console.log("Correct Password!");
          resolve(true);
        }
        // Also add an else here, to ensure the promise always ends:
        else {
          resolve(false);
        }
      }
    });
  });
}
+1
source

C async:

async function authenticate(uname, pword) {
    return await User.find({ username: uname }, 'password').then(function (result) { ... })
};

Without async:

function authenticate(uname, pword) {
    return User.find({ username: uname }, 'password').then(function (result) { ... })
};
+1
source

, . . authenticate / , . , .

/* This function doesnt need to be async */
function authenticate(uname, pword) {
  return new Promise((resolve, reject) => {
    User.find({username: uname}, 'password', function (err, result) {
      if (err !== null) {
        /* I think this should be reject(err) but since you wish to have it resolved in your code, i have kept resolve()*/
        resolve(false);
      }
      else {
        if (pword === result[0].password) {
          console.log("Correct Password!");
          resolve(true);
        }
      }
    })
  });
}
+1
source

Source: https://habr.com/ru/post/1690659/


All Articles