【问题标题】:Typescript asynchronous call with mariadb使用 mariadb 的 Typescript 异步调用
【发布时间】:2021-05-08 05:30:25
【问题描述】:

我做错了什么? 我声明了这个方法。我不确定它是否正确。

async getTutorials() : Promise<Tutorial[]> {
  
  return await mariadb.createConnection(Config.db)
    .then(conn => {
      conn.query('select * from tutorial')
        .then(rows => {
          rows.forEach(row => {
            console.log(row);
          });
          conn.end();
          return new Promise(rows);
        })
        .catch(err => {
          //handle query error
          return [];
        });
    })
    .catch(err => {
      //handle connection error
      return [];
    });   
  }
}

那我想在那个方法里面调用这个方法。

export const getTutorials: RequestHandler = async (req, res, next) => {
    
    let tutorials = await tutorialService.getTutorials();
    console.log(tutorials);
    res.status(200).json({tutorials});
}

此方法的控制台日志打印一个未定义的对象。第一种方法的日志正确打印​​了对象。 我不知道如何将数组从第一种方法转移到第二种方法。

【问题讨论】:

    标签: typescript methods async-await


    【解决方案1】:

    花点时间理解 Promise!您不应该捕获(和忽略)错误,如果您使用.then(),则不需要await。您也不需要在 then 回调中使用 new Promise

    两个核心问题是您正在使用嵌套的 Promise(也不是一个好主意,您想链接),并且内部 Promise 不会返回到外部 Promise。另一个问题是您将查询结果 (rows) 传递给 new Promise(),但 new Promise 期望收到回调,而不是结果。您可能打算在这里使用Promise.resolve(),但根本不需要。

    解决所有这些问题会导致:

    async getTutorials() : Promise<Tutorial[]> {
      
      return mariadb.createConnection(Config.db)
        .then(conn => {
          return conn.query('select * from tutorial');
        })
        .then(rows => {
          conn.end();
          return rows;
        })
     
      }
    }
    

    但是,使用 await 可以进一步简化:

    async getTutorials() : Promise<Tutorial[]> {
      const conn = await mariadb.createConnection(Config.db);
      const rows = await conn.query('select * from tutorial');
      conn.end();
      return rows;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2016-11-11
      • 2015-02-19
      • 2020-03-25
      • 2022-11-29
      • 2016-09-23
      • 1970-01-01
      • 2021-02-07
      • 2018-01-01
      相关资源
      最近更新 更多