首页 > 解决方案 > JavaScript 回调在 Chrome 中出现故障?

问题描述

我试图在另一个函数完成后调用一个函数。通常,这是通过回调完成的,至少在 Node.js 中是这样。但是,当我尝试在 Chrome 中运行以下代码时,回调函数似乎在主函数之前执行。我写错了我的函数/回调吗?第二个函数(回调函数)不应该只在第一个函数完成后执行吗?

如果当javascript在浏览器中运行客户端时回调不起作用,是否有另一种方法可以确保第二个函数仅在第一个函数完成时运行?

<html>
<head></head>
<body>
<script>

function firstLoad(callback) {
  console.log("firstLoad function fired.");
}

function secondLoad() {
  console.log("secondLoad function fired.");
}

firstLoad(secondLoad());

</script>
</body>
</html>

在 Chrome 开发者工具控制台中,上面的代码给了我:

secondLoad 函数被触发。

firstLoad 函数被触发。

我希望它会反过来。

标签: javascriptwebcallback

解决方案


我试图在这里给出一个更简单的答案,直截了当,我已经编辑了你的代码,所以它按照你期望的方式工作,并添加了一些评论来解释正在发生的事情:

<html>
  <head></head>
  <body>
  <script>

    function firstLoad(callback) { //secondLoad is "saved" in the callback variable
      console.log("firstLoad function fired.");

      //When Firstload is done with doing all it has to do you have to manually call 
      //the callback which references to the secondLoad function:
      callback();
    }

    function secondLoad() {
      console.log("secondLoad function fired.");
    }

    //Here you pass the secondLoad function as a parameter for the firstLoad function,
    //in your code you were passing the *result* of secondLoad
    firstLoad(secondLoad); 

  </script>
  </body>
</html>

我假设 firstLoad 没有做异步的东西,比如网络请求


推荐阅读