代码之家  ›  专栏  ›  技术社区  ›  Trung Tran

带有knexjs的异步系列

  •  0
  • Trung Tran  · 技术社区  · 10 年前

    有没有一种方法可以将回调数据存储在异步响应中的对象中?

    例如,在下面的示例中,我需要通过数组索引访问对象( response[0], response[1] 等)。但我想像这样访问它 response.user_employed 响应.user_employed 。我的代码如下。提前谢谢!

    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
    
            }   
    );
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   George Chen    10 年前

    你需要的是并联或串联

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

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

    });

    推荐文章