【问题标题】:Async/await with function push not working [duplicate]功能推送的异步/等待不起作用[重复]
【发布时间】: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()returnedcallback2 未在 sendNotification 中定义
  • 不清楚 getNewNotification 和 sendNotification 是如何关联的,问题不包含 stackoverflow.com/help/mcve 。你在滥用async。它不应该与回调一起使用。 node-postgres 支持 Promise。

标签: javascript node.js node-postgres


【解决方案1】:

我认为这是因为你混合了两件事,要么你应该使用没有 await 语句的回调方法,要么你应该正确使用 Promise。在您的情况下,您可以使用 -

修复它

不是这个

await pool.query(`SELECT * from wfm where mail = '${user.id}''`, async (err, res) => {

});

你应该使用 -

let response = await pool.query(`SELECT * from wfm where mail = '${user.id}'`)

你的回调代码可以放在底部。

更多详情可以参考-https://node-postgres.com/guides/async-express

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 2019-04-22
    • 1970-01-01
    • 2020-01-11
    • 2022-01-22
    • 2016-12-05
    • 2019-11-05
    相关资源
    最近更新 更多