【问题标题】:Wait for all query to finish and fill at the same time asynchronously等待所有查询完成并同时异步填充
【发布时间】:2015-02-26 00:59:24
【问题描述】:

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

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

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 接近我想要的但不知道如何实现

【问题讨论】:

  • 是我遗漏了什么还是您的代码不包含循环?另外,这种半递归方式不是已经奏效了吗?您想改进什么?
  • 是否有任何理由按顺序而不是并行运行这些查询?
  • 没有任何理由,你能告诉我更多吗?并感谢您的快速响应

标签: node.js promise bluebird knex.js


【解决方案1】:

我认为您正在寻找map method,该map method 适用于数组的承诺,并将为其中的每个项目调用异步(承诺返回)回调:

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});
});

【讨论】:

  • 我会试着告诉你它是怎么回事
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 2020-02-22
  • 1970-01-01
  • 2016-07-07
  • 2016-03-16
  • 2020-10-04
  • 2016-01-15
  • 2011-10-04
相关资源
最近更新 更多