我有以下JS代码:
<script>
first();
second();
</script>
我想确保second()
会在first()
完全执行完成后运行。这是预期的默认行为吗?
我有以下JS代码:
<script>
first();
second();
</script>
我想确保second()
会在first()
完全执行完成后运行。这是预期的默认行为吗?
这取决于您在first()
和second()
函数内部拥有什么。如果存在一些异步调用,first()
可能会在second()
之后结束。
例如:
function first(){
console.log("I'm first");
}
function second(){
console.log("I'm second");
}
first();
second();
将会打印
我是第一个
我是第二个
现在假设你在你的first()
函数中有一个ajax调用,需要10秒才能结束:
function first(){
$.ajax({
//--- blah blah
success: function(){
//--- success runs after 10 seconds
console.log("I'm first");
}
})
}
如果你运行
first();
second();
您将会打印
我是第二个
我是第一个
这里 您可以找到另一个例子
http://krasimirtsonev.com/blog/article/7-lines-JavaScript-library-for-calling-asynchronous-functions
http://jsbin.com/AhirAlOV/5/edit?html,js,output
重要提示:Javascript 中大部分的函数都是同步的。如果你想要依次调用多个同步函数
first();
second();
它们将按顺序执行。second
将在first
完成之前不会开始。