javascript - 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 函数被触发。
我希望它会反过来。
解决方案
我试图在这里给出一个更简单的答案,直截了当,我已经编辑了你的代码,所以它按照你期望的方式工作,并添加了一些评论来解释正在发生的事情:
<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 没有做异步的东西,比如网络请求
推荐阅读
- ios - Swift,FirebaseAuth:取消链接提供者 user.providerData 后仍包含 providerID
- python - 将 Python 与带有 IF 语句的 Schedule 库一起使用
- c# - 如何在 Visual Studio 中删除调试器建议的约束
- java - 为什么 Spring Security 身份验证会导致 CORS 错误
- syntax - 在文本输入下创建按钮时如何修复错误?
- python - 2个字符串之间的删除距离的算法问题
- c# - Is it possible to distinguish between attachments added with drag and drop and via the attachment menu button
- node.js - node-archiver 在 aws lambda 中不起作用
- c# - 集成测试 EF Core + AutoMapper ProjectTo
- r - R循环字符串并使用它来引用列名