简体   繁体   English

如何在返回结果之前等待 javascript 完成所有功能

[英]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但在检查 codeverify function 之前,即使 codeverify() function 返回 false,它也会将 output 返回为 true

PS. 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.这归结为您如何编写 JavaScript 代码,我发现通常何时到达我的程序不同步的地步,这意味着我在前面的步骤中做错了。 This is usually only fixed by refactoring.这通常只能通过重构来解决。

Remember JavaScript does not behave the same as other languages.请记住 JavaScript 的行为与其他语言不同。

What I can see from your procedure is that you are trying to do many things in one go.从您的程序中我可以看出,您正试图在一个 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.为每个步骤声明一个单独的 function,即使您的 function 只有一行要执行。

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.尝试构建每个 function 以接收和返回一些东西。

Another tip that I can give is, write your procedure to select and hold elements in variables until they are required.我可以给出的另一个提示是,将您的程序写入 select 并将元素保存在变量中,直到需要它们为止。 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.考虑执行时需要哪些元素,其中哪些在执行开始时在 dom 中,并在开始执行之前将它们设置为变量,然后在执行期间是否添加了以后可能需要的元素dom,这意味着当你的程序执行时,所有的成分都可以用来做任何必须做的事情,他们不必 go 即时找到他们需要的东西。

Good Luck and happy coding.祝你好运,编码愉快。

Your coderesult.confirm(code) using promise( then & catch ) so i assume it is asynchronous.你的coderesult.confirm(code)使用 promise( then & catch ) 所以我认为它是异步的。 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. JS 行为的一件重要事情是,如果两者之间存在异步 function,JS 总是处理代码的 rest。

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.在您的情况下,您的codeverify function 之间有异步代码( .confirm() ),因此 JS 将在codeverify之后处理代码( return output )直到codeverify完全完成。

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 .由于您的output从一开始就设置为true ,因此它将在您的代码codeverify完成之前从最后一行代码返回truereturn output ,这就是为什么您总是得到true If you change the first row output = undefined , i believe you will see undefined result.如果您更改第一行output = undefined ,我相信您会看到undefined的结果。

To solve this, one of the way is you can wrap the entire codeverify as Promise .要解决这个问题,一种方法是您可以将整个codeverify包装为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:您可以像这样执行 function:

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.最后,花点时间研究一下什么是异步以及 Promise 与异步做什么,因为它在 JS 中无处不在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让function等待其他函数完成后再执行 - How to make function wait for other functions to finish before executing 如何让程序在继续使用javascript之前等待if语句完成? - How to make the program wait for the if statement to finish before continuing in javascript? 如何等待API调用完成然后返回结果? - How to wait for API calls to finish and then return the result? 如何使 for 循环等待所有异步函数完成。 异步函数里面有多个异步函数 - How to make for loop wait for all async functions to finish. async functions has multiple async functions inside in it JavaScript:4个异步函数要依次等待对方完成才能继续? - JavaScript: 4 asyncronys functions to wait for each other sequentially to finish before continuing? 如何在Javascript中让等1的方法完成其他 - How to make wait the 1 method to finish other in Javascript 我如何让我的 javascript 函数在继续之前等待 WebSql 事务完成 - How i make my javascript function wait to WebSql transactions to finish before continuing 我如何让 javascript 循环在开始下一次循环之前等待循环的每次迭代完成? - How do i make javascript loop wait for each iteration of loop to finish before starting the next? 如何让 Node.js 后端 JavaScript 在做任何其他事情之前等待我的 bash 脚本完成 - How to make Node.js backend JavaScript wait for my bash script to finish before doing anything else 等待函数按顺序完成Javascript - Wait for a functions to finish in sequence Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM