【发布时间】:2023-03-31 08:11:01
【问题描述】:
async - await 有问题。
发生了什么?
我有一个回调函数,它向其他函数发送一个对象数组,其中包含有效对象和无效对象。
在函数中,我进行验证,如果有效,然后执行push 将其保存在数组中。
我想将它传递给另一个函数,当它最终确定所有对象都有效时。但它通过一个一个而不是全部。
有人可以帮助我吗?
我调用回调的函数传递对象数组是否有效:
const getNewNotification = async (callback) => {
await pool.query('SELECT * from alerts', (err, res) => {
if (err) {
console.log(err)
} else {
const newsNotification = res.rows;
callback(newsNotification)
}
})
}
我制作push的功能:
const sendNotification = async (notification, callback) => {
let domain;
let subdomain;
let name;
let userHistory;
let userDescription;
let sequenceHistory;
let personYes = [];
let person;
await notification.map(async (user) => {
// VERIFY IF THE OBJECT IS VALID
await pool.query(`SELECT * from wfm where mail = '${user.id}''`, async (err, res) => {
if (res.rows.length !== 0) {
person = {
domain: res.rows[0].domain_name,
subdomain: res.rows[0].subdomain_name,
name: res.rows[0].name,
userHistory: user.id,
userDescription: user.change_description,
sequenceHistory: user.sequence,
}
// MAKE THE PUSH...
await personYes.push(person);
callback2(personYes);
}
基本上,我希望函数sendNotification 在它结束时发送数据,我是怎么做到的?
【问题讨论】:
-
没有值是来自
.map()的returned。callback2未在sendNotification中定义 -
不清楚 getNewNotification 和 sendNotification 是如何关联的,问题不包含 stackoverflow.com/help/mcve 。你在滥用
async。它不应该与回调一起使用。 node-postgres 支持 Promise。
标签: javascript node.js node-postgres