如果我执行类似 $location.path('new/path')
的路径更改,此路径更改下方的代码会发生什么情况?据我了解,路径更改不会阻止其余代码运行,但实际发生了什么?代码会结束,然后路径才会改变吗?因此,如果此代码非常耗时(比如在慢速网络连接上将某些内容保存到服务器),那么位置更改是否会同样迟到?或者事情会并行发生吗?
最佳答案
Here's a small test ,看起来它完成了代码的运行,然后更改了位置。查看 jsfiddle 中的控制台,您会看到两个循环都在运行,但一个接一个。
正如@SilverlightFox 指出的那样,javascript 中没有并行处理。
//this one loads first, executes the loop, then changes location.
function HomeCtrl($scope, $location) {
$location.path('/about');
var i = 0;
while(i < 1000000000) {
if(i % 100000000 === 0) {
console.log('home')
}
i++;
}
}
//this loop executes second.
function AboutCtrl($scope) {
$scope.name = 'John';
var i = 0;
while(i < 1000000000) {
if(i % 100000000 === 0) {
console.log('about')
}
i++
}
}
如果code in
HomeCtrl
is changed要包含超时,位置首先发生变化,因为超时中断了程序的流程并将超时安排在AboutCtrl
之后执行。执行。//changes location first, executes AboutCtrl, then does the "home" loop
function HomeCtrl($scope, $location) {
$location.path('/about');
setTimeout(function() {
var i = 0;
while(i < 1000000000) {
if(i % 100000000 === 0) {
console.log('home')
}
i++;
}
}, 1)
}
带 proper async request它与超时相同:位置更改,'about' 循环运行,然后 http 请求完成。因此,在慢速连接上更新数据库的 ajax 调用不会阻止应用程序更改路由。
//changes location, executes 'AboutCtrl', then finishes the http request and
//executes the 'home' loop.
function HomeCtrl($scope, $location, $http) {
$location.path('/about');
$http.get('/echo/json/').success(function() {
var i = 0;
while(i < 1000000000) {
if(i % 100000000 === 0) {
console.log('home')
}
i++;
}
});
如果我改变路线 因为网络电话 ,我会在成功/错误 promise 或回调中这样做,如果这是意图的话。
关于angularjs - 当 $location.path ('new/path' 下方有代码时会发生什么)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30969718/