GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Missing await — CodeQL query help documentation

Missing await¶

ID: js/missing-await
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - javascript-code-quality.qls
   - 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 the await operator or call the then method. Attempting to use a promise object instead of its underlying value can lead to unexpected behavior.

Recommendation¶

Use the await operator to get the value contained in the promise. Alternatively, call then on the promise and use the value passed to the callback.

Example¶

In the following example, the getData function returns a promise, and the caller checks if the returned promise is 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;
  }
  // ...
}

However, the null check does not work as expected. The return null statement on line 2 actually returns a promise containing the null value. Since the promise object itself is not equal to null, the error check is bypassed.

The issue can be corrected by inserting await before the promise:

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;
  }
  // ...
}

References¶

  • MDN: Using promises

  • MDN: Async functions

  • MDN: Await operator

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.