【发布时间】:2014-05-19 15:27:09
【问题描述】:
我正在编写一个 JavaScript API。 API 返回使用 Kris Kowal(和贡献者)的 Q Promise 库创建的 Promise。在大多数情况下,我似乎不必在应用程序本身中引用 Q,这是我喜欢的,因为它使我选择的 Promises-library 对使用我的 API 进行开发的人来说是透明的。 (到目前为止)我似乎遇到问题的唯一方法是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()?
【问题讨论】:
标签: javascript asynchronous promise q