Ember js:在我的例子中,为什么路由器中的逻辑会继续,即使其中使用的功能还没有完成

Ember js: In my example why does the logic in the router continue even though the function used in it has not completed?

本文关键字:js 继续 功能 还没有 为什么 Ember 路由器 我的      更新时间:2023-09-26

我是ember js的新手,我正在努力理解路由:)

这是我的控制器代码:

App.AppController = Em.ArrayController.extend({
login: App.Login.create({}),
loginUser: function(){
    $.ajax({
        type: 'POST',
        cache: false,
        url: contextPath + 'user/register',
        data:{name:this.login.name, email:this.login.email,password:this.login.password,confirmPassword:this.login.confirmPassword,acceptTerms:this.login.acceptTerms},
        success: function(data) {
            alert('success!');
        },
        error: function(jqXHR, textStatus, errorThrown) {
        }
    });
}
})

下面是我使用这个函数的地方:

App.ChooseServiceIndexRoute = Em.Route.extend({
redirect: function() {
    var isLoggedIn = this.controllerFor('app').loginUser();
    alert(isLoggedIn);
    if(isLoggedIn){
        this.transitionTo('chooseService');
    }
    else {
        this.transitionTo('app');
    }
}
});

看起来,函数loginUser被调用了,但是alert(isLoggedIn)在函数完成之前发生了(alert(success)在alert(isLoggedIn)之后发生。

我需要一些帮助来理解发生了什么事。

谢谢!

Ajax意味着异步Javascript和XML,所以根据定义它是异步的,这意味着它在完成之前不会停止代码,而是在完成加载后运行回调。您可以将async设置为false,以便在完成之前停止执行。不过,您必须小心超时和类似的情况。

查看这里可用的选项:$。ajax文档