Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Missing await

ID: js/missing-awaitKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - correctnessQuery suites:   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

In JavaScript,async functions always return a promise object. To obtain the underlying value of the promise, use theawait operator or call thethen method. Attempting to use a promise object instead of its underlying value can lead to unexpected behavior.

Recommendation

Use theawait operator to get the value contained in the promise. Alternatively, callthen on the promise and use the value passed to the callback.

Example

In the following example, thegetData function returns a promise, and the caller checks if the returned promise isnull:

asyncfunctiongetData(id){letreq=awaitfetch(`https://example.com/data?id=${id}`);if(!req.ok)returnnull;returnreq.json();}asyncfunctionshowData(id){letdata=getData(id);if(data==null){console.warn("No data for: "+id);return;}// ...}

However, the null check does not work as expected. Thereturnnull statement on line 2 actually returns apromise containing thenull value. Since the promise object itself is not equal tonull, the error check is bypassed.

The issue can be corrected by insertingawait before the promise:

asyncfunctiongetData(id){letreq=awaitfetch(`https://example.com/data?id=${id}`);if(!req.ok)returnnull;returnreq.json();}asyncfunctionshowData(id){letdata=awaitgetData(id);if(data==null){console.warn("No data for: "+id);return;}// ...}

References


[8]ページ先頭

©2009-2025 Movatter.jp