Seraphim
Seraphim

Reputation: 11

Handling Async Function

I have the following function:

export function readUserData(userName, password) {
  firebase.database().ref("users/" + userName).once("value").then(function (snap) {
    //console.log(snap.val().salt);
    var verification = passwordVerify(password, snap.val().salt);
    //console.log(verification);
    //console.log(snap.val().password);
    console.log(snap.val());
    return snap.exists() && snap.val().password === verification 
      ? userAuth.located = snap.val()
      : userAuth.located = false;
  });
  return userAuth.located;
}

I am told that firebase.database().ref is an asynchronous function, and it seems to be so in that it returns userAuth.located in the final line of readUserData before writing console.log(snap.val());
How do I ensure that firebase.database().ref... executes before I return the final result? I am unsure how to implement await/promises into this code as the overall function is not asynchronous.

Upvotes: 0

Views: 77

Answers (2)

aashah7
aashah7

Reputation: 2195

You should return the promise, like:

export function readUserData(userName, password) {
    return firebase.database().ref("users/" + userName)
      .once("value")
      .then(function (snap) {
        var verification = passwordVerify(password, snap.val().salt);
        return snap.exists() && snap.val().password === verification 
          ? snap.val()
          : false;
    });
}

Then, whichever code calls this method, should also async-await:

var userAuthLocated = await readUserData(userName, password);

or, with promises:

readUserData(userName, password)
  .then(userAuthLocated => {
    // use userAuthLocated here
  });

Upvotes: 2

Greg M
Greg M

Reputation: 405

To address your comment above @Seaphin. There is one more step needed with the following line

var userAuthLocated = await readUserData(userName, password);

What is happening is that your app is using userAuthLocated before it updates. userAuthLocated does get updated by the firebase call in readUserData, however, you are missing an async() function.

Using await should always be wrapped in an async () function call. It should look something similar to this

userAuth = async () => {
    var userAuthLocated = await readUserData(userName, password);
    //setstate or
    return userAuthLocated

Essentially using async "blocks" until the value is ready to use. Functions waiting on that value won't execute until the async function unblocks

Upvotes: 0

Related Questions