假设我有以下功能:
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/