javascript - 如何以非静态形式使用 Q.all?

标签 javascript asynchronous promise q

我正在编写一个 JavaScript API。 API 返回使用 Kris Kowal(和贡献者)的 Q promises 库创建的 promises。在大多数情况下,我似乎不必在应用程序本身中引用 Q,我喜欢这一点,因为它使我对使用我的 API 进行开发的人透明地选择了 Promises-library。我似乎遇到麻烦的唯一方法(到目前为止)是 Q.all() .

Q API 引用指出“此方法通常以其静态形式使用”。是否可以以非静态形式(或其他方式)使用 Q.all() 以便我不需要引用 Q?

例如获取系列中的人和工作(我不想要系列。虚构的例子):

MyApplication.prototype.renderTeam = function(name) {

  var that = this;

  myAPI
    .getTeam({name: name})
    .then(function(data) {
      that.team = data;
    })

    // list of all people
    .then(function() {
      return myAPI.getPeople();
    })
    .then(function(data) {
      that.people = data;
    })

    // list of all jobs
    .then(function(data) {
      return myAPI.getJobs();
    })
    .then(function(data) {
      that.jobs = data;
    })

    // render template
    .then(function() {
      var template = $('#template'}.html();
      var content = Mustache.render(template, {
        team: that.team,
        people: that.people,
        jobs: that.jobs
      })
      $('#view').html(content);
    })
    .fail(function(err) {
      alert(err.message);
    })
  ;
};

我想用 .all 和 .spread(或任何其他方式)并行获取所有人员和工作,但不引用 Q,但这行不通:

MyApplication.prototype.renderTeam = function(name) {

  var that = this;

  myAPI
    .getTeam({name: name})
    .then(function(data) {
      that.team = data;
    })

    // list of all people and jobs.
    // broken here.
    .all([
      myAPI.getPeople(),
      myAPI.getJobs()
    ])
    .spread(function(people, jobs) {
      that.people = people;
      that.jobs = jobs;
    })

    // render template
    .then(function() {
      var template = $('#template'}.html();
      var content = Mustache.render(template, {
        team: that.team,
        people: that.people,
        jobs: that.jobs
      })
      $('#view').html(content);
    })
    .fail(function(err) {
      alert(err.message);
    })
  ;
};

有没有正确的方法来完成这个?我是否必须添加 API 方法 getAll()?

最佳答案

  myAPI
    .getTeam({name: name})
    .then(function(data) {
      that.team = data;
      return [
        myAPI.getPeople(),
        myAPI.getJobs()
      ];
    })
    .all()
    .spread(function(people, jobs) {
      that.people = people;
      that.jobs = jobs;
    })

关于javascript - 如何以非静态形式使用 Q.all?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23741605/

相关文章:

javascript - 从 WebSQL 中的 javascript 将 currentDate 插入 WebSQL 时出现问题

javascript - 跳出 javascript 嵌套的 async.each 循环但继续主循环

asynchronous - 不再使用时是否应该关闭 clojure core.async channel ?

node.js - promise 运行 then() 但不返回正确的数据

javascript - 如何使用window.fetch加载本地json数据(ES6)

javascript - Javascript 中加载事件的竞争条件

javascript - 制作了有问题的图像点击计数器

asp.net - RadMaskedTextBox 的掩码可以通过 javascript 更改吗?

JAVA/如何使用comletable-future进行异步回调?

javascript - 在 JavaScript 中等待两个异步命令