Trung Tran
Trung Tran

Reputation: 13721

Async series with knexjs

Is there a way I can store callback data in an object in an async response?

For example, in my example below, I need to access objects by their array index (response[0], response[1], etc.). But I want to access it like response.user_employed or response.user_employed. My code is below. Thanks in advance!

async.waterfall(
    [

        function uno(callback) {
            knex('user').where({
                employed: true
            }).then(function(data) {
                callback(data);
            }).catch(function(error) {
                console.log('error: ' + error);
            });
        },

        function dos(callback) {


            knex('user').where({
                employed: false
            }).then(function(data) {
                callback(data);
            }).catch(function(error) {
                console.log('error: ' + error);
            });
        }],

        function(err, response) {

            console.log(response[0]); // returns data from function uno
            console.log(response[1]); // returns data from function dos

        }   
);

Upvotes: 0

Views: 265

Answers (1)

George Chen
George Chen

Reputation: 6939

parallel or series is what you need

async.parallel([
function(callback){
        knex('user').where({
            employed: true
        }).then(function(data) {
            callback(data);
        }).catch(function(error) {
            console.log('error: ' + error);
        });
},
function(callback){
        knex('user').where({
            employed: false
        }).then(function(data) {
            callback(data);
        }).catch(function(error) {
            console.log('error: ' + error);
        });
   }
],
// optional callback
function(err, results){
     console.log(response[0]); // returns data from function 1
     console.log(response[1]); // returns data from function 2
});

or

async.series({
  employed:     function(callback){
        knex('user').where({
            employed: true
        }).then(function(data) {
            callback(data);
        }).catch(function(error) {
            console.log('error: ' + error);
        });
  },
  umemployed:  function(callback){
        knex('user').where({
            employed: false
        }).then(function(data) {
            callback(data);
        }).catch(function(error) {
            console.log('error: ' + error);
        });
  }
 },
 function(err, results) {
  console.log(results.employed);
  console.log(results.unemployed);

});

Upvotes: 1

Related Questions