使用 returns 承诺的函数异步映射 collection
Asyncronously mapping over a collection with a function that returns a promise
我正在尝试学习如何使用 Bluebird 承诺,但我有点迷茫。
我有两个数据库 table:topic
和 subject
。
topic
table 有一个 subject_id
列,然后可用于查询 subject
table 的主题标题。
我有一个 orm
异步查询并且 return 是一个承诺。
最终,我正在尝试为主题编写一个模型方法来为您进行查找,将后续 subject
查询中的 subject_title
returned 注入到每个元素中object 的数组最初是从 topic
查询中 return 编辑的。
我正在尝试使用 Promise.map
,但这不起作用。下面的代码不起作用。我从没想过会这样,但我认为它抓住了我想要完成的事情的本质。
var promise = orm.select({
db: db,
table: 'topic',
where: args.where,
order: args.order,
limit: args.limit,
offset: args.offset,
group: args.group
}).map(function (topic) {
var promise = orm.select({
db: db,
table: 'subject',
qrm: 'one',
where: {id: topic.subject_id}
}).then(function (subject) {
topic.subject_title = subject;
});
return promise;
});
return promise;
因此,假设原版 topic
object 具有以下属性:
[subject_id, title, description]
而 subject
object 有:
[id, title]
我希望上述函数 return 具有以下属性的 object 数组:
[subject_id, subject_title, title, description]
完成此任务最干净的方法是什么?
您似乎只需要 return 来自您的 .then()
处理程序的修改后的 topic
对象,以便它保持已完成的值:
return orm.select({
db: db,
table: 'topic',
where: args.where,
order: args.order,
limit: args.limit,
offset: args.offset,
group: args.group
}).map(function (topic) {
return orm.select({
db: db,
table: 'subject',
qrm: 'one',
where: {id: topic.subject_id}
}).then(function (subject) {
topic.subject_title = subject;
// Add return here so topic stays the fulfilled value
return topic;
});
});
顶层promise的fullfilled值应该是修改后的topic对象数组。
我正在尝试学习如何使用 Bluebird 承诺,但我有点迷茫。
我有两个数据库 table:topic
和 subject
。
topic
table 有一个 subject_id
列,然后可用于查询 subject
table 的主题标题。
我有一个 orm
异步查询并且 return 是一个承诺。
最终,我正在尝试为主题编写一个模型方法来为您进行查找,将后续 subject
查询中的 subject_title
returned 注入到每个元素中object 的数组最初是从 topic
查询中 return 编辑的。
我正在尝试使用 Promise.map
,但这不起作用。下面的代码不起作用。我从没想过会这样,但我认为它抓住了我想要完成的事情的本质。
var promise = orm.select({
db: db,
table: 'topic',
where: args.where,
order: args.order,
limit: args.limit,
offset: args.offset,
group: args.group
}).map(function (topic) {
var promise = orm.select({
db: db,
table: 'subject',
qrm: 'one',
where: {id: topic.subject_id}
}).then(function (subject) {
topic.subject_title = subject;
});
return promise;
});
return promise;
因此,假设原版 topic
object 具有以下属性:
[subject_id, title, description]
而 subject
object 有:
[id, title]
我希望上述函数 return 具有以下属性的 object 数组:
[subject_id, subject_title, title, description]
完成此任务最干净的方法是什么?
您似乎只需要 return 来自您的 .then()
处理程序的修改后的 topic
对象,以便它保持已完成的值:
return orm.select({
db: db,
table: 'topic',
where: args.where,
order: args.order,
limit: args.limit,
offset: args.offset,
group: args.group
}).map(function (topic) {
return orm.select({
db: db,
table: 'subject',
qrm: 'one',
where: {id: topic.subject_id}
}).then(function (subject) {
topic.subject_title = subject;
// Add return here so topic stays the fulfilled value
return topic;
});
});
顶层promise的fullfilled值应该是修改后的topic对象数组。