我正在编写一个 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/