node.js - 等待所有查询完成并同时异步填充

标签 node.js promise bluebird knex.js

我想用其他查询填充查询结果的每个对象,并且我想以异步方式完成所有操作

这是我实际操作方式的示例

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/

相关文章:

node.js - Hapijs - 服务器重新启动时 HttpOnly cookie 消失

javascript - 在 Javascript 中分析异步函数

javascript - 为什么这些 promise 没有解决?

node.js - 在下载模块中使用 promises

javascript - 验证输入是否是用户名或电子邮件

javascript - Nodemon每次重启前执行函数

javascript - 无法弄清楚如何将 yield 与异步请求一起使用

javascript - Bluebird Promise.all 在 Promise 链中间捕获并继续 Promise

javascript - 如何监听另一个对象的事件发射?

node.js - 使用 Mocha 测试 Express : a promise-based test will not run by itself?