繁体   English   中英

存储来自多个回调node.js javascript的数据

[英]Store data from multiple callbacks node.js javascript

我正在使用knexjs ORM从我的postgresql数据库中检索数据。 有没有一种方法可以更干净地存储来自多个数据库请求的数据? 目前,我正在这样做:

knex('user').where({
    approved: true
}).then(function(data) {
    context.approved = data;
    knex('user').where({
        unapproved: true
    }).then(function(data) {
        context.unapproved = data;
        console.log(context); //this is my main objective
    }).catch(function(error) {
        console.log('error: ' + error);
    });
}).catch(function(error) {
    console.log('error: ' + error);
});

如果我需要提出更多请求,这很容易变得非常混乱。 理想情况下,我想执行以下操作:

function a(callback) {

    knex('user').where({
        approved: true
    }).then(function(data) {
        //store this data somehow
    }).catch(function(error) {
        console.log('error: ' + error);
    });
};

function b(callback) {

    knex('user').where({
        unapproved: true
    }).then(function(data) {
        //storethis data somehow
    }).catch(function(error) {
        console.log('error: ' + error);
    });
};

function c(a, b) {
    //do an operation with the data returned from functions a and b
}

但是,我不确定100%如何实现这一点。 有人可以帮忙吗?

提前致谢!

我认为您想研究诺言。 您可以使用Promise.all()异步执行所有数据调用。

Promise.all([a, b]).then(function(value) { 
  console.log(value);
}, function(reason) {
  console.log(reason) 
});

文档: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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