【问题标题】:How to make this variable execture after i get the data? [duplicate]获取数据后如何使该变量执行? [复制]
【发布时间】:2022-02-17 00:21:26
【问题描述】:

我不知道问题出在哪里,我知道标题没有描述我对此的任何看法。 这是我面临的问题。 我目前正在使用 MERN 应用程序。

我有一条快递路线,我从两个表中请求数据库中的一些数据。

playlist.post("/getplaylistSongs", (req, res) => {
  const { cookie } = req.body;
  const sql = "SELECT * FROM playlist WHERE user_id = ?";
  dbCon.query(sql, [cookie], (err, result) => {
    if (err) {
      res.status(400).json({
        message: "failed to get playlist details ",
      });
    } else {
      let playlistSongs = [];
      result.forEach((element, index) => {
        const audio_id = element.audio_id;
        dbCon.query(
          "SELECT * FROM audios where video_id = ?",
          [audio_id],
          (err, song) => {
            if (err) {
              res.status(400).json({
                message: "failed to get music",
              });
            } else {
              playlistSongs.push(song);
            }
          });
      });
     console.log(playlistSongs); 

      res.status(200).json({
        playlist: playlistSongs,
      });
    }
  });
});

但是这里的问题是我尝试这样做我总是将playlistSongs 作为一个空数组。 谢谢你。评论以纠正问题。

编辑:现在我知道问题与 javascript 的执行有关。

【问题讨论】:

  • dbCon.query 是异步的。以 (err, song) 开头的回调将是您可以访问响应数据的地方。
  • 谢谢你,但我现在更困惑@You

标签: javascript node.js express scope


【解决方案1】:

试试async / await:

playlist.post('/getplaylistSongs', async (req, res) => {
  const { cookie } = req.body;
  const sql = 'SELECT * FROM playlist WHERE user_id = ?';
  try {
    const result = await dbCon.query(sql, [cookie]);

    let playlistSongs = [];
    result.forEach(async (element, index) => {
      const audio_id = element.audio_id;
      const song = await dbCon.query(
        'SELECT * FROM audios where video_id = ?',
        [audio_id]
      );
      playlistSongs.push(song);
    });
    console.log(playlistSongs);

    res.status(200).json({
      playlist: playlistSongs,
    });
  } catch (e) {
    res.status(400).json({
      message: 'failed to get playlist details ',
    });
  }
});

【讨论】:

  • 感谢您的回复,感谢您的帮助,但遇到语法错误,您介意看看吗` const song = await dbCon.query( ^^^^^ SyntaxError: await is only valid在异步函数和模块的顶层主体中`
  • 我忘记将内部forEach 函数声明为async。检查编辑的答案。
猜你喜欢
  • 2020-03-11
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多