我想用其他查询填充查询结果的每个对象,并且我想以异步方式完成所有操作
这是我实际操作方式的示例
var q = knex.select().from('sector');
q.then(function (sectores) {
var i = -1;
(function getDetalles(sectores) {
i++;
if(i < sectores.length){
knex.select().from('sector_detalle')
.where('sector_id', sectores[i].id)
.then(function (detalles) {
// this what i want to do asynchronously
sectores[i].sector_detalles = detalles;
console.log(sectores[i]);
getDetalles(sectores);
});
} else {
res.send({sucess: true, rows: sectores});
}
})(sectores);
});
我做了一些研究,发现了这个 wait for all promises to finish in nodejs with bluebird 接近我想要的但不知道如何实现
最佳答案
我认为您正在寻找 map
method它适用于数组的 promise ,并将为其中的每个项目调用异步( promise 返回)回调:
knex.select().from('sector').map(function(sector) {
return knex.select().from('sector_detalle')
.where('sector_id', sector.id)
.then(function(detalles) {
sector.sector_detalles = detalles;
// console.log(sector);
return sector;
});
}).then(function(sectores) {
res.send({sucess: true, rows: sectores});
});
关于node.js - 等待所有查询完成并同时异步填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28732689/