【问题标题】:Trying to understand Async/Await试图理解异步/等待
【发布时间】:2020-06-06 02:26:44
【问题描述】:

我有一个异步函数“查询”,它“等待”pool.query 返回结果。

// db.js

const pool = new pg.Pool({
  connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
  ssl: isProduction,
});

export const query = async ({ text, values }) => {
  const start = Date.now();

  try {
    const results = await pool.query(text, values);
    const duration = Date.now() - start;
    logger.info(`executed query: ${text} duration: ${duration} rows: ${results.rowCount}`);
    return results.rows;
  } catch (e) {
    logger.error(`error: ${e}`);
  }
};

在另一个异步函数 getUser() 中,我正在“等待”查询函数在返回数据之前完成。


// users.js

export const getUser = async (email) => {
  const text = `
      SELECT (user_id, email) FROM users 
      WHERE email = $1
  `;
  const values = [email];

  try {
    const data = await query({ text, values });
    // ^ vscode says above await is doing nothing
    return data.rows[0];
  } catch (e) {
    logger.error(`error: ${e}`);
  }
};

然后在另一个异步函数中,我正在等待 getUser 函数


// auth.js

export const SignIn = async (email, password) => {
  const userRecord = await getUser(email);
  if (!userRecord) {
    throw new Error('User not registered');
  }

  logger.silly('Checking password');
  const validPassword = await argon2.verify(userRecord.password, password);
  if (validPassword) {
    logger.silly('Password is valid!');
    logger.silly('Generating JWT');
    const token = await generateToken(userRecord);

    const user = { id: userRecord.id, email: userRecord.email };
    return { user, token };
  } else {
    throw new Error('Invalid Password');
  }
};

在 vsCode 内部,我收到一条警告“等待对此表达式的类型没有影响。”仅在“等待”查询函数调用时,而不是在“等待”getUser 函数调用时。我在这里错过了什么?

【问题讨论】:

  • 任何用async 定义的函数都会返回一个Promise,等待一个promise 会产生效果。也许您正在导入另一种称为查询的方法。根据显示的代码,警告是虚假的。
  • 我只有一个查询功能。
  • 顶部有import {query} from './db'吗?
  • 是的,我有 import { query } from '../loaders/db.js'
  • 就可以了。 VS Code 将遵循 .js 文件中的 JSDoc cmets。对于异步函数,返回类型推断,I.E.在@returns {type} 中去掉{type} 可能会更好。否则你必须写@returns {Promise<something>}

标签: javascript asynchronous async-await


【解决方案1】:

query 返回什么?如果results.rows 是一个承诺,那么这可能会解释您所看到的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2019-09-16
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
相关资源
最近更新 更多