简体   繁体   English

如何创建具有多个 AJAX 属性的 javascript 对象?

[英]How to create a javascript object with multiple AJAX properties?

I have a javascript project with legacy code.我有一个带有遗留代码的 javascript 项目。 There is creating an object with properties via synchronous ajax.有通过同步 ajax 创建一个具有属性的对象。 Something like this:像这样的东西:

function App() {
  this.users = $.parseJSON(
    $.ajax({
      url: '/users'
      datatype: "json"
      async: false
    }).responseText);

  this.items = $.parseJSON(
    $.ajax({
      url: '/items'
      datatype: "json"
      async: false
    }).responseText);

  this.pets = $.parseJSON(
    $.ajax({
      url: '/pets'
      datatype: "json"
      async: false
    }).responseText);
}

Of course, this properties are avalible in the object after initialization.当然,这些属性在初始化后在对象中是可用的。 But now, I need to rewrite it with async Ajax requests.但是现在,我需要用异步 Ajax 请求重写它。 So, here is my question: is there a best practice to create an object with many Ajax properties?所以,这是我的问题:是否有创建具有许多 Ajax 属性的对象的最佳实践?

PS: I have an idea — to use promises chain and create object after all requests. PS:我有一个想法——在所有请求之后使用承诺链并创建对象。 But I want to know: is there any solutions?但我想知道:有什么解决办法吗?

Your idea is very close.你的想法很接近。 It's not so much a chain , the ajax calls can run in parallel, but you need to know when they've all finished.与其说是,不如说是 ajax 调用可以并行运行,但是您需要知道它们何时全部完成。 jQuery has just the thing for you: $.when : jQuery 正好适合您: $.when

function App() {
    var t = this;
    t.readyPromise = $.when(
        $.ajax({
          url: '/users',
          dataType: "json",
          success: function(data) {
              t.users = data;
          }
        }),
        $.ajax({
          url: '/items',
          dataType: "json",
          success: function(data) {
              t.items = data;
          }
        }),
        $.ajax({
          url: '/pets',
          dataType: "json",
          success: function(data) {
              t.pets = data;
          }
        })
    );
}

Since App looks like a constructor, I'll note that the instance you get from new App() won't be ready to use until its readyPromise resolves.由于App看起来像一个构造函数,我会注意到您从new App()获得的实例在其readyPromise解析之前不会准备好使用。 You might reorganize the code so that you don't have a partially-constructed object (partially-constructed objects tend to be a bad idea).您可能会重新组织代码,以便没有部分构造的对象(部分构造的对象往往是一个坏主意)。 We can also make use of the way $.when collects the results of promises for us:我们还可以利用$.when的方式为我们收集 promise 的结果:

function App(users, items, pets) {
    this.users = users;
    this.items = items;
    this.pets = pets;
}
App.get = function() {
    return $.when(
        $.ajax({
          url: '/users',
          dataType: "json"
        }),
        $.ajax({
          url: '/items',
          dataType: "json"
        }),
        $.ajax({
          url: '/pets',
          dataType: "json"
        })
    ).then(function(users, items, pets) {
        return new App(users, items, pets);
    });
};

Usage:用法:

App.get().then(function(app) {
    // use `app` here
});

Live Example:现场示例:

 function fakeAjax(opts) { var d = $.Deferred(); setTimeout(function() { d.resolve(["some " + opts.url.substring(1)]); }, Math.floor(Math.random() * 500)); return d.promise(); } function App(users, items, pets) { this.users = users; this.items = items; this.pets = pets; } console.log("Getting..."); App.get = function() { return $.when( fakeAjax({ url: '/users', dataType: "json" }), fakeAjax({ url: '/items', dataType: "json" }), fakeAjax({ url: '/pets', dataType: "json" }) ).then(function(users, items, pets) { return new App(users, items, pets); }); }; // Usage: App.get().then(function(app) { console.log(app); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Side note: It's dataType , not datatype ;旁注:它是dataType ,而不是datatype I've fixed it in the above.我已经在上面修复了它。 There were also essential missing commas.也有必不可少的缺失逗号。

Good idea ;)好主意;)

$.when($.ajax({
  url: '/users'
  datatype: "json"
}), $.ajax({
  url: '/item'
  datatype: "json"
}),  $.ajax({
  url: '/pets'
  datatype: "json"
})).done(function(users, item, pets) {
//blabla
});

You have already learned that Javascript variables are containers for data values.您已经了解到 Javascript 变量是数据值的容器。

This code assigns a simple value ( "Fiat" ) to a variable named car :此代码将一个简单的值( "Fiat" )分配给名为car的变量:

var car = "Fiat";

Objects are variables too.对象也是变量。 But objects can contain many values.但是对象可以包含许多值。

This code assigns many values ( "Fiat" , "500" , "white" ) to a variable named car :此代码将许多值( "Fiat""500""white" )分配给名为car的变量:

var car = {type:"Fiat", model:"500", color:"white"};

For more information see Object Properties有关更多信息,请参阅对象属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM