Return a promise that contains an array with data from other promises

0

I am setting up a function in expresJS that using two simple functions execute two SQL queries using Knex to two different databases, but it must return as a response a promise.

function qDB1(status_id) {
  return KnexDB1
  .select()
  .from('table1')
  .where({
    status: status_id
  })
  .orderBy('date')
  .catch(function(err) {
    console.log(err);
  });
}

function qDB2 () {
  var dateStart=Moment().format('L');
  var dateEnd=Moment().add(1, 'days').format('L');
  return KnexImc
  .raw("EXEC SP_DB2 'QU', '"+dateStart+"','"+dateEnd+"'")
  .catch(function(err) {
    console.log(err);
  });
}

QueryRepo.prototype.select = function(status_id) {

  if ( !status_id) {
    status_id=1;
  }
  var results = [];

  qDB1(status_id)
  .then(function (res) {
    for(var idx = 0; idx < res.length; idx++){
      console.log(res[idx]);
      results.push(res[idx]);
    }
  });
  qDB2()
  .then(function (res) {
    for(var idx2 = 0; idx2 < res.length; idx2++){
      console.log(res[idx2]);
      results.push(res[idx2]);
    }
  });

  return Promise.all(results);

};

When I execute the functions qDB1 and qDB2 work well and load the data in results , the problem is that when executing select the promise arrives as an empty array.

I know I could return the resuls array once the Knex promises are completed, but the answer needs to be a promise.

    
asked by Damian Olguin 18.01.2017 в 05:07
source

1 answer

1

You are misusing the Promise.all . I recommend you to see how it works here . Basically the Promise.all receives as promises parameter. If you look closely, in select you should do the following:

return Promise.all([qDB1(status_id), qDB2()]).then(function(values){
    // Merge the two query results
    var promiseResults = values[0].concat(values[1]);

    var results;

    for(var idx = 0; idx < promiseResults.length; idx++){
        results.push(promiseResults[idx]);
    }
    // Returns a promise with the results
    return Promise.resolve(results);
}).catch(function(error){
    console.log(error);
});
  • Take the catch of qDB1 and qDB2 .

This would return a promise . Therefore when you call select you should use:

select().then(function(results){
    console.log(results);
});
    
answered by 19.01.2017 / 19:05
source