title: How can i excute code sequentially in JavaScript
body: <p>I had a problem. I am writing a method that first checks if the user exists with a condition if not it will insert the action and I am using a flag variable to control the flow. but there is a problem which is the exception is not sequentially instead it goes down tho if(!flag) after that go up to check if the user exists or not </p>
  
  <pre class="lang-js prettyprint-override"><code>analysis = actionid =&gt; {
    //check if it is't the first command
    console.log("before definition of flage");
    var flag = false;
    console.log("hiii");
    firebase
      .database()
      .ref("userActions/")
      .once("value", snap =&gt; {
        console.log("iafter definition ");
        snap.forEach(child =&gt; {
          if (
            child.val().userID === firebase.auth().currentUser.uid &amp;&amp;
            child.val().ActionID == actionid
          ) {
            plus = parseInt(child.val().Repetition) + 1;
            console.log("before first use");
            flag = true;
            firebase
              .database()
              .ref(child)
              .set((Repetition = plus))
              .then(() =&gt; {
                console.log("inserted the update");
              })
              .catch(error =&gt; {
                console.log(error);
              });
          }
        });
      });
  
    console.log("before second use");
    if (!flag) {
      console.log("inside second use");
      var userActionKey = firebase
        .database()
        .ref()
        .child("userActions")
        .push().key;
      firebase
        .database()
        .ref("userActions/" + userActionKey)
        .set({
          userID: firebase.auth().currentUser.uid,
          ActionID: "001",
          time: "12",
          Repetition: "1"
        })
        .then(() =&gt; {
          console.log("inserted");
        })
        .catch(error =&gt; {
          console.log(error);
        });
    }
  };
  </code></pre>