我正在尝试在 Node js 中创建一个函数,该函数读取数据库值并将它们插入数组中,然后最后返回该数组。我的功能目前如下所示:
function getInvoicesCount() {
let promiseInvoices = [];
let userInvCount = 0;
let deletedUserInvCount = 0;
let userInvAmount = 0;
let deletedUserInvAmount = 0;
let monthWiseInvCount = [];
db.userInvoices
.findAll({
attributes: [
'deleted_at',
[sequelize.fn('COUNT', sequelize.col('id')), 'count'],
[sequelize.fn('SUM', sequelize.col('invoice_amount')), 'amount'],
[sequelize.fn('MONTH', sequelize.col('invoice_date')), 'month']
],
group: ['invoice_date', 'deleted_at'],
paranoid: false
})
.then(result => {
result.forEach(function(element) {
userInvCount += element.dataValues.count;
userInvAmount += element.dataValues.amount;
if (element.dataValues.deleted_at != null) {
deletedUserInvAmount += element.dataValues.amount;
deletedUserInvCount += element.dataValues.count;
}
monthWiseInvCount.push(element.dataValues);
});
if (monthWiseInvCount.map(a => a === 'deleted_at')) {
monthWiseInvCount.map(a => delete a.deleted_at);
}
promiseInvoices.push(
userInvCount,
userInvAmount,
deletedUserInvCount,
deletedUserInvAmount,
monthWiseInvCount
);
});
return promiseInvoices;
}
在代码的主要部分,我想调用这个函数并使用 .then 来获取返回的数组
你能帮我看看如何在函数中返回一个 promise 以及如何在 .then 部分中访问该数组吗?
最佳答案
以下是您需要进行的更改才能获得预期结果:
function getInvoicesCount() {
...
return db.userInvoices.findAll({ //<-------- 1. First add return here
...
}).then(result => {
...
return promiseInvoices; //<----------- 2. Put this line inside the then
});
// return promiseInvoices; //<----------- Remove this line from here
}
getInvoicesCount().then(data => {
console.log(data); // <------- Check the output here
})
Explanation for this :
To get
.then
when you can function , function should returnpromise
, but in you case you are just returning a blank array ,As per the sequlize doc ,
db.userInvoices.findAll
returns the promise so all you need to do is addreturn
before the this function , First step is doneYou were
return promiseInvoices;
at wrong place , why ? , coz at that you will never get the result , as the code above it run in async manner as it is promise , so you will always get the balnk array , to get the expected result you should return it fromdb.userInvoices.findAll
'sthen
function as shown above in code
关于javascript - Node js - 返回从sequelize数据库读取的对象数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50597009/