没有 Ember 数据的 AJAX 承诺 [英] AJAX promise without Ember Data

查看:24
本文介绍了没有 Ember 数据的 AJAX 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定不使用 ember-data,因为它尚未准备好用于生产并且仍在变化.无论如何,我的应用程序只需要发出一些 ajax 请求,所以它不应该有太大的不同.我无法理解如何处理 ajax 承诺响应.

I have decided to not use ember-data as it's not production ready and still changing. My app only needs to make a few ajax requests anyway so it shouldn't make too big of a difference. I am having trouble understanding how to handle an ajax promise response.

当我的用户加载应用程序时,他们已经拥有一个经过身份验证的会话.我正在尝试为该用户信息 ping 服务器并将其显示在我的模板中.我的模板似乎是在我的 ajax 请求返回结果之前呈现的,然后没有更新承诺.

When my user loads the app they already have an authenticated session. I am trying to ping the server for that users info and display it in my template. It seems my template is rendered before my ajax request returns results and then does not update with the promise.

// route
App.ApplicationRoute = Ember.Route.extend({
    setupController: function(){
        this.set("currentUser", App.User.getCurrentUser());
    }
});


// model
App.User = Ember.Object.extend({
    email_address: '',
    name_first: '',
    name_last: '',
    name_full: function() {
        return this.get('name_first') + ' ' + this.get('name_last');
    }.property('name_first', 'name_last')
});
App.User.reopenClass({
    getCurrentUser: function() {
        return $.ajax({
            url: "/api/get_current_user",
            type: "POST",
            data: JSON.stringify({})
        }).then(function(response) {
            return response;
        });
    }
});

在我的模板中:

<h1> Hey, {{App.currentUser.name_first}}</h1>

如何在收到响应时更新模板或延迟呈现直到收到响应?

How would I update the template when I receive a response or delay rendering until I have a response?

推荐答案

其实答案很简单:你不需要使用 promise.而是只返回一个空对象.您的代码可能如下所示:

Actually the answer is quite easy: You do not need to use a promise. Instead just return an empty object. Your code could look like this:

App.User.reopenClass({
    getCurrentUser: function() {
        var user = App.User.create({}); //create an empty object
        $.ajax({
            url: "/api/get_current_user",
            type: "POST",
            data: JSON.stringify({})
        }).then(function(response) {
            user.setProperties(response); //fill the object with your JSON response
        });
        return user;
    }
});

这里发生了什么?

  1. 您创建了一个空对象.
  2. 您对 API 进行了异步调用...
  3. ...并且在您的成功回调中填充您的空对象.
  4. 您返回用户对象.

注意:到底发生了什么? 上面提到的流程并不是这些操作发生的顺序.实际上,首先执行第 1,2 和 4 点.然后一段时间后,当响应从您的服务器返回时,将执行 3.所以真正的动作流程是:1 -> 2 -> 4 -> 3.

Note: What is really happening? The flow mentioned above is not the sequence in which those actions are happening. In reality the points 1,2 and 4 are performed first. Then some time later, when the response returns from your server, 3 is executed. So the real flow of actions is: 1 -> 2 -> 4 -> 3.

所以一般规则是始终返回一个对象,使 Ember 能够执行其逻辑. 在您的情况下,不会首先显示任何值,一旦您的对象被填充,Ember 将开始发挥其魔力,并且自动更新您的模板.无需在您身边做任何艰苦的工作!

So the general rule is to always return an object that enables Ember to do its logic. No values will be displayed first in your case and once your object is filled Ember will start do its magic and auto update your templates. No hard work needs to be done on your side!

超越最初的问题:如何用数组做到这一点?按照这个一般规则,您将返回一个空数组.这里有一个小例子,它假设您可能希望从后端获取所有用户:

Going beyond the initial question: How would one do this with an array? Following this general rule, you would return an empty array. Here a little example, which assumes, that you might like to get all users from your backend:

App.User.reopenClass({
    getAllUsers: function() {
        var users = []; //create an empty array
        $.ajax({
            url: "/api/get_users",
        }).then(function(response) {
            response.forEach(function(user){
                var model = App.User.create(user); 
                users.addObject(model); //fill your array step by step
            });
        });
        return users;
    }
});

这篇关于没有 Ember 数据的 AJAX 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆