SyntaxError: await is only valid in async function in Nodejs

Dung Do Tien Jun 25 2022 50

Hi you guys, I have created a small Nodejs application, that will help pull a list of user information from an API and display it on the browser. I used express to help create a web server with local port 5000.

I use node-fetch package to help fetch data from an API, you can see like this:

const fetch = require('node-fetch');
var express = require('express');
var app = express();

app.get('/', function (req, res) {
        const result = await getUser();
        console.log(result);
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});


async function getUser() {
    try {
      const response = await fetch('https://randomuser.me/api/');
  
      if (!response.ok) {
        throw new Error(`Error! status: ${response.status}`);
      }
  
      const result = await response.json();
      return result;
    } catch (err) {
      console.log(err);
    }
}

I  used fetch() method as an async method but when running the code above I got an exception : SyntaxError: await is only valid in async function.

SyntaxError: await is only valid in async function
←[90m    at wrapSafe (internal/modules/cjs/loader.js:1053:16)←[39m
←[90m    at Module._compile (internal/modules/cjs/loader.js:1101:27)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:985:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:878:14)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)←[39m
←[90m    at internal/main/run_main_module.js:17:47←[39m

I use Node version v12.18.3.

Please help me if you have any solution.

Thank you in advance.

Have 1 answer(s) found.
  • A

    Akarsh Pissey Jun 25 2022

    Note important: You call the async B method inside the A method. The A method has to async method too.

    Solution:  make the app.get() as an async method. See the example below:

    // A method
    app.get('/', async (req, res) =>  { // update this line change from synchonous to asynchronous
            const result = await getUser();
            console.log(result);
    });
    
    // B method
    async function getUser() {
        try {
          const response = await fetch('https://randomuser.me/api/');
      
          if (!response.ok) {
            throw new Error(`Error! status: ${response.status}`);
          }
      
          const result = await response.json();
          return result;
        } catch (err) {
          console.log(err);
        }
    }

    It will solve the issue for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close