简体   繁体   English

Javascript,节点 Promise {<pending> } 用 try catch azync</pending>

[英]Javascript, NodeJS Promise { <pending> } with try catch azync

Hi i have 3 endpoint (diferents querys but same methodologie) and i want to create a function to reduce the amounts of lines in my code.您好,我有 3 个端点(不同的查询但相同的方法),我想创建一个 function 来减少代码中的行数。

example of my endpoint (Working and tested)我的端点示例(工作和测试)

 router.get("/timeFrame/vocal_word", authenticateToken, async (req, res) => {
  const query =
    "SELECT max(vocal_word.user_id) AS user_id, \
      AVG(vocal_word.score) AS avg_score, \
      SUM(vocal_word.score) AS sum_score, \
      COUNT(*) AS total_inputs, \
      min(vocal_word.`date`) AS oldest_date, \
      max(vocal_word.`date`) AS newest_date, \
      case \
        when TIME(`date`) between '00:00:00' and '05:59:59' then 3 \
        when TIME(`date`) between '06:00:00' and '09:29:59' then 8 \
        when TIME(`date`) between '09:30:00' and '12:29:59' then 11 \
        when TIME(`date`) between '12:30:00' and '15:29:59' then 14 \
        when TIME(`date`) between '15:30:00' and '18:29:59' then 17 \
        when TIME(`date`) between '18:30:00' and '23:59:59' then 20 \
      end as 'time_intervals' \
    FROM vocal_word \
    WHERE  `date` >= CURRENT_TIMESTAMP() - interval ? DAY AND vocal_word.user_id = ? \
    GROUP BY time_intervals \
    ORDER BY time_intervals ASC";

  try {
    const day = 1 + " Day";
    const week = 6 + " days → 1 week";
    const month = 30 + " days → 1 Month";
    const year = 365 + " days → 1 Year";
    const total = 5000 + " days → Total";

    let intervalFrame = [day, week, month, year, total];
    let result = [];

    for (let i = 0; i < intervalFrame.length; i++) {
      const outputQuery = await poolPromise.query(query, [
        intervalFrame[i],
        req.user.userId,
      ]);

      outputQuery[0].forEach((item) => {
        item["interval_frame"] = intervalFrame[i];
      });

      result = [...result, ...outputQuery[0]];
    }

    res.status(200).json(result);
  } catch (error) {
    res.status(500).json("Please contact back-end service");
  }
});

Not working不工作

Now when i want to take out the variables and the loop is not working and response with an status 200 with an empty object现在,当我想取出变量并且循环不工作并以状态 200 和空 object 响应时

async function getTimeFrames(query, userId) {
  const day = 1 + " Day";
  const week = 6 + " days → 1 week";
  const month = 30 + " days → 1 Month";
  const year = 365 + " days → 1 Year";
  const total = 5000 + " days → Total";

  try{
    let intervalFrame = [day, week, month, year, total];
    let result = [];

    for (let i = 0; i < intervalFrame.length; i++) {
      const outputQuery = await poolPromise.query(query,    [intervalFrame[i], userId]);

      outputQuery[0].forEach((item) => {
        item["interval_frame"] = intervalFrame[i];
      });

      return (result = [...result, ...outputQuery[0]]);
    }
  } catch(error) {
    console.log(error);
  }
}

the console.log(error) shows [Promise{<pending>}] console.log(error)显示[Promise{<pending>}]

The endpoint + the query端点+查询

router.get("/timeFrame/test", authenticateToken, async  (req, res, next) => {
  const query =
    "SELECT max(vocal_word.user_id) AS user_id, \
    AVG(vocal_word.score) AS avg_score, \
    SUM(vocal_word.score) AS sum_score, \
    COUNT(*) AS total_inputs, \
    min(vocal_word.`date`) AS oldest_date, \
    max(vocal_word.`date`) AS newest_date, \
    case \
      when TIME(`date`) between '00:00:00' and '05:59:59'   then 3 \
      when TIME(`date`) between '06:00:00' and '09:29:59'   then 8 \
      when TIME(`date`) between '09:30:00' and '12:29:59'   then 11 \
      when TIME(`date`) between '12:30:00' and '15:29:59'   then 14 \
      when TIME(`date`) between '15:30:00' and '18:29:59'   then 17 \
      when TIME(`date`) between '18:30:00' and '23:59:59'   then 20 \
    end as 'time_intervals' \
  FROM vocal_word \
  WHERE  `date` >= CURRENT_TIMESTAMP() - interval ? DAY AND     vocal_word.user_id = ? \
  GROUP BY time_intervals \
  ORDER BY time_intervals ASC";

  try {
    let result = getTimeFrames(query, req.user.userId);
    console.log([result]);

    res.status(200).json(result);
  } catch (error) {
    next(error)
  }
});

I know the query works no doubts on that.我知道查询对此毫无疑问。 And i founded some questions related to these topic with.then and here i want to do it with try-catch我发现了一些与这些主题相关的问题。然后在这里我想用 try-catch 来做

Ok, after looking at your code, I noticed two things:好的,在查看您的代码后,我注意到两件事:

  1. You are trying to return the results inside the for loop in the getTimeFrames function:您正试图在getTimeFrames function 的 for 循环内返回结果:
async function getTimeFrames(query, userId) {
  const day = 1 + " Day";
  const week = 6 + " days → 1 week";
  const month = 30 + " days → 1 Month";
  const year = 365 + " days → 1 Year";
  const total = 5000 + " days → Total";

  try{
    let intervalFrame = [day, week, month, year, total];
    let result = [];

    for (let i = 0; i < intervalFrame.length; i++) {
      const outputQuery = await poolPromise.query(query,    [intervalFrame[i], userId]);

      outputQuery[0].forEach((item) => {
        item["interval_frame"] = intervalFrame[i];
      });

      // Here, you have to change this
      // return (result = [...result, ...outputQuery[0]]);
      result = [...result, ...outputQuery[0]]
    }
    // And return the value outside of the loop
    return result;
  } catch(error) {
    console.log(error);
  }
}
  1. The function is an asynchronous function, so it will return a promise, you need to handle that: function是一个异步的function,所以会返回一个promise,你需要这样处理:
// Here you already defined your function as async 
// so you can use the await keyword to get the promise content
router.get("/timeFrame/test", authenticateToken, async  (req, res, next) => {
  const query =
    "SELECT max(vocal_word.user_id) AS user_id, \
    AVG(vocal_word.score) AS avg_score, \
    SUM(vocal_word.score) AS sum_score, \
    COUNT(*) AS total_inputs, \
    min(vocal_word.`date`) AS oldest_date, \
    max(vocal_word.`date`) AS newest_date, \
    case \
      when TIME(`date`) between '00:00:00' and '05:59:59'   then 3 \
      when TIME(`date`) between '06:00:00' and '09:29:59'   then 8 \
      when TIME(`date`) between '09:30:00' and '12:29:59'   then 11 \
      when TIME(`date`) between '12:30:00' and '15:29:59'   then 14 \
      when TIME(`date`) between '15:30:00' and '18:29:59'   then 17 \
      when TIME(`date`) between '18:30:00' and '23:59:59'   then 20 \
    end as 'time_intervals' \
  FROM vocal_word \
  WHERE  `date` >= CURRENT_TIMESTAMP() - interval ? DAY AND     vocal_word.user_id = ? \
  GROUP BY time_intervals \
  ORDER BY time_intervals ASC";

  try {
    // Here you need to await for the result like this:
    let result = await getTimeFrames(query, req.user.userId);
    console.log([result]);

    res.status(200).json(result);
  } catch (error) {
    next(error)
  }
});

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

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