简体   繁体   中英

how to make wait javascript to finish all functions before return result

output = true;

if($("#password-field").css('display') != 'none') {
    if(!($("#verificationCode").val())) {
        output = false;
        $("#code-error").html("required");
    }   

    var codeverify =  function(){

    var code = document.getElementById("verificationCode").value;
    coderesult
        .confirm(code)
        .then( function(result) {
            if (result.user.uid) {
                let phoneNumber =  result.user.phoneNumber;
                //alert(output);
                 alert("Verification done");
                console.log(phoneNumber);

            } else {
                alert(output);
                $("#code-error").html("no user");
                  output = false;
            }
        })
        .catch(function(error) {
            output = false;
            $("#code-error").html("wrong");
            alert(error.message);
        });

        }();

}

return output;

When i run this code everything works fine. but before checking the codeverify function it return the output to true even if the codeverify() function returns false

PS. I am using wizard form.

This comes down to how you write JavaScript code, I found that usually when to get to a point where my procedures are out of sync it means that I have done something wrong in previous steps. This is usually only fixed by refactoring.

Remember JavaScript does not behave the same as other languages.

What I can see from your procedure is that you are trying to do many things in one go.

Although I do not have a solution I have a suggestion, consider each action that you want your procedure to execute. Declare a separate function for each of these steps, even if your function only has one line to execute.

If there are dependencies make sure they can be resolved by parameterization.

And lastly, think pure functions. Try and structure every function to receive something and return something.

Another tip that I can give is, write your procedure to select and hold elements in variables until they are required. Consider what elements are required in execution, which of those are in the dom when execution starts and set them to variables before you start executing, then during execution if elements are added that are maybe required for later select them immediately after they are placed in the dom, this means that as your procedure executes all the ingredients are available to do whatever must be done they don't have to go find what they need on the fly.

Good Luck and happy coding.

Your coderesult.confirm(code) using promise( then & catch ) so i assume it is asynchronous. You need to google yourself to learn what is async

One important thing of JS behavior is JS always process the rest of the code if there is a async function in between.

Sample:

 console.log(1) setTimeout(()=>{ console.log(2,"i suppose at position 2 but i'm at the last. This is because setTimeout is async function") },1000) console.log(3)

In your case, your codeverify function has async code ( .confirm() ) in between, so JS will process the code after codeverify ( return output )until codeverify is fully completed.

Since your output was set at true since the beginning, it will return true from the last row of code return output before your codeverify completed, this is why you always get true . If you change the first row output = undefined , i believe you will see undefined result.

To solve this, one of the way is you can wrap the entire codeverify as Promise .

function codeverify(){
   return new Promise((resolve,reject)=>{
      var code = document.getElementById("verificationCode").value;
        coderesult.confirm(code).then( function(result) {
            if (result.user.uid) {
                let phoneNumber =  result.user.phoneNumber;
                //alert(output);
                alert("Verification done");
                console.log(phoneNumber);
                output = true
                resolve(output)

            } else {
                alert(output);
                $("#code-error").html("no user");
                output = false;
                resolve(output)
            }
        }).catch(function(error) {
            output = false;
            $("#code-error").html("wrong");
            alert(error.message);
            reject(output) //you can reject(error.message) so you can pass error message back.
        });
   })
}

You can execute the function like this:

codeverify().then(successData=>{
   console.log(successData) //from what you resolve
}).catch(failedData=>{
   console.log(failedData) //from what you reject
})

Lastly, take some time to study what is Asynchronous and What Promise to do with Async because it is everywhere in JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM