Reputation: 47
I want my function to return, after the ((querySnapshot) => {...
function is finished.
At the moment, my noOpponent
function returns always false
after calling, Thats probably because its returning, before the ((querySnapshot) => {...
function is finished and so its returned, before the state
is set true
. I already tried to call the noOpponent function with var a = await noOpponent(key)
, but its not working, because as i already wrote, I think i have to await for the ((querySnapshot) => {...
function. How can I do this?
export const noOpponent = (Key) => {
var state = false;
console.log("key: " + Key)
duettsRef
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get()
.then((querySnapshot) => {
console.log("QuerysnapshotResult: " + !querySnapshot.empty);
state = true;
})
return state;
};
Upvotes: 0
Views: 104
Reputation: 83181
The other answers propose to use async
/await
, which is very good and recommended for code readability.
Let's show here how you should do if you still want to use then()
:
export const noOpponent = (Key) => {
var state = false;
console.log("key: " + Key)
return duettsRef // <=== See the return here. More at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get()
.then((querySnapshot) => {
console.log("QuerysnapshotResult: " + !querySnapshot.empty);
state = true;
return state; // See how we call return in the then block and not outside of it
});
};
Note that the noOpponent()
function is asynchronous and returns a Promise.
Upvotes: 2
Reputation: 7418
That is a perfect fit for async/await
. It turns async code to something like sync code. You would need to write your code like this:
export const noOpponent = async (Key) => {
var state = false;
console.log("key: " + Key)
const querySnapshot = await duettsRef
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get()
console.log("QuerysnapshotResult: " + !querySnapshot.empty);
state = true;
return state;
};
Make sure when you call noOpponent
to also use async or then.
noOpponent('key').then(state=>{
console.log('state',state)
})
Upvotes: 1
Reputation: 1133
Try this code:
export const noOpponent = async (Key) => {
var state = false;
console.log("key: " + Key)
let querySnapshot = await duettsRef
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get();
// do something like assign value to state then return
return state;
};
Upvotes: 1