缺少 await¶
ID: js/missing-await
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- correctness
Query suites:
- javascript-security-and-quality.qls
在 JavaScript 中,async
函数始终返回一个 Promise 对象。要获取 Promise 的基础值,请使用 await
运算符或调用 then
方法。尝试使用 Promise 对象而不是其基础值会导致意外行为。
建议¶
使用 await
运算符来获取 Promise 中包含的值。或者,在 Promise 上调用 then
并使用传递给回调的值。
示例¶
在以下示例中,getData
函数返回一个 Promise,并且调用方检查返回的 Promise 是否为 null
async function getData(id) {
let req = await fetch(`https://example.com/data?id=${id}`);
if (!req.ok) return null;
return req.json();
}
async function showData(id) {
let data = getData(id);
if (data == null) {
console.warn("No data for: " + id);
return;
}
// ...
}
但是,null 检查没有按预期工作。第 2 行上的 return null
语句实际上返回一个包含 null
值的 *Promise*。由于 Promise 对象本身不等于 null
,因此错误检查被绕过。
可以通过在 Promise 之前插入 await
来纠正此问题
async function getData(id) {
let req = await fetch(`https://example.com/data?id=${id}`);
if (!req.ok) return null;
return req.json();
}
async function showData(id) {
let data = await getData(id);
if (data == null) {
console.warn("No data for: " + id);
return;
}
// ...
}
参考资料¶
MDN:使用 Promise
MDN:异步函数
MDN:Await 运算符