0

i'm using firebase, so my function has an async nested function and looks like this:

  var invld = 0;
  ref.child(userId).orderByChild('name').equalTo(listName).on("value", 
  function(snapshot) {
    if (snapshot.exists()){
      invld = 1;
      alert(invld);
      return false;
    }
  });
  alert(invld);
  if (invld == 1) {
    // exit from the main function
    overwritePrompt();
    return false;
  }else{
    // Save on firebase
    database.ref().child('users').child(userId).push('list').set(data);
  }

it doesn't work because var invld is always 0, being updated inside the async function, how can i fix this situation?

  • Thanks i got it now, any chances you can point me out how can i fix my code if part of it is async? –  Sep 21 '18 at 16:52
  • 1
    Basically, the snapshot is only available to you in the callback function, so, either put everything into the `function(snapshot) {` or, call a function from that callback and pass it the snapshot as a parameter – Luca Kiebel Sep 21 '18 at 16:59

1 Answers1

0

Your code is async, thus the function won't be called until all your sync code has completed. You should move all your check inside the callback then your code will execute correctly.

  ref.child(userId).orderByChild('name').equalTo(listName).on("value", 
  function(snapshot) {
    if (snapshot.exists()){
      overwritePrompt();
      return false;
    } else {
      database.ref()
        .child('users').child(userId).push('list').set(data);
    }
  });
hasanain
  • 764
  • 5
  • 12
  • Ok i got rid of the downward code so i don't need the return false things. Now the problem is with your solution, if snapshot DOESN'T exist the item is pushed then automatically shows the Prompt anyway. (so from my understanding it goes into "else" correctly, and then read the function again by itself and now of course snapshot exists so it launches the Prompt anyway.) –  Sep 21 '18 at 17:40
  • You can add some external state that you set inside the callback the first time and then use that to display the prompt – hasanain Sep 25 '18 at 05:37