0

Here I have a function that is supposed to return either true or false whether or not the document is present in the collection. The query works fine and the result in the console log actually displays the correct boolean value to be returned.

async function isClaimed(voucher, user) {
  var db = Firebase.firestore();
  var result;
  
  await db
    .collection("ClaimedVoucher")
    .where("voucherID", "==", voucher)
    .where("userID", "==", user)
    .get()
    .then(function (querySnapshot) {
      if (querySnapshot.empty === false) {
        result = true;
      } else {
        result = false;
      }
    })
    .catch(function (error) {
      console.log("Error getting documents: ", error);
    }); 
  console.log(result, "this is result");
  return result;
}

However, when I console log what is returned (outside the function), it is the promise, not the boolean value:

isVoucherClaimed = isClaimed(voucher.voucherID, uid);
          console.log(isVoucherClaimed);

Displays:

Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, }

I've read that async functions always return promises, however if I remove the async/await then the "result" variable is always undefined, even inside the function. Any help would be greatly appreciated - I am new to react-native / javascript.

1 Answer 1

2

You already have a hint - async functions will always return a promise. In order to get the value, you need to wait for it to get fulfilled or rejected. Either use await or .then().

isVoucherClaimed = await isClaimed(voucher.voucherID, uid);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response! However, I am calling the "isVoucherClaimed" function in my main function that returns JSX - I can't use await in that function because I'd have to turn it into an async function. Do you know what I mean? I forgot to mention I am using functional components and not classes.
@kiermcguirk You should not have async code running on the root of the component - it should probably be in a useEffect or an event handler. Anyways, this is as far as I can guess without actually seeing the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.