javascript - 等待不返回 promise 的异步方法是否被明确视为不良做法?

标签 javascript node.js async-await

假设我有以下功能:

const someFunc = async(obj) => {
    const { x, y } = obj;
    const result = await devices.update(
        { x: x, y: y },
        { $set: { z: 1 } },
        { upsert: false }
    );
    if (result.nModified !== 1) throw new Error("Some error");
    return result;
};

我这样调用它:

try {
    await someFunc();
catch (err) {
    console.log(err);
}

我无法返回 device.update(...),因为我需要对函数内修改的文档数执行测试。我也知道 someFunc() 将返回的结果包装在 Promise 对象中,但不确定这段代码是否被认为是干净的代码。

最佳答案

您的代码看起来有效。如果你跳过 await 那么它不会等到它解析了里面的 Promise 。相反,它将返回值视为已解决的 Promise。来自 await 的文档:

If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.

所以我做了一个简单的例子,只是为了看看有没有 await 关键字的区别。

请考虑以下代码。

(async () => {
  console.log('async function started');
  const runAsync = async (value) => {
    const result = await new Promise(resolve => {
      setTimeout(() => resolve(value), 2000);
    });
    return result;
  };

  const dataWithoutAwait = runAsync('value');
  console.log('data without await', dataWithoutAwait);

  const dataAwait = await runAsync('value');
  console.log('data with await', dataAwait);
})();

我希望这能澄清并帮助您解决问题。

关于javascript - 等待不返回 promise 的异步方法是否被明确视为不良做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564106/

相关文章:

javascript - 如何在不折叠的情况下将div绘制到特定位置已经存在的div或没有覆盖

javascript - 在 WooCommerce 产品页面中添加千位分隔符和总价

javascript [array].splice 不工作 ("Uncaught TypeError: collisions.splice is not a function")

node.js - 如何从 AWS RDS 连接到没有 "database"名称的 PostgreSQL 数据库

.net - 我们是否总是需要使用 async 关键字?

javascript - 在 Node.js 中获取没有扩展名的文件的 MIME 类型

node.js - 如何从react.js发送数据到node?

javascript - Promise.all 和 Promise.race 有效地做出所有 promise "handled"是记录在案的行为吗?

typescript - 在 Protractor `await` 上使用 `element().getAttribute()` 给出错误 : "Type of ' await' operand must either be a valid promise. .."

node.js - 到 'ws://chattestarpit.herokuapp.com/' 的 WebSocket 连接失败 : Error during WebSocket handshake: Unexpected response code: 503