简体   繁体   中英

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

        }   
);

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM