0

In Nodejs v16.15.1, I can easily assign axios respond to a variable.

const clientlist = await axios.get('http://test.lab/api/getclients');

However, when I upgraded to latest Nodejs v19.6.0, I keep getting error: await is only valid in async functions.

So, I tried to change the code as per below

var uid1 = 0;

async function getUID() {
  let res = await axios.get('http://test.lab/api/?user=test');
  let data = res.data;
  return data;
}

// Call start
(async() => {
  console.log('before start, the value is '+ uid1);

  uid1 = await getUID1();
  
  console.log('after start, the value is '+ uid1);
})();

//trying to use uid1 for the rest of the code

console.log('outside async, the value is '+ uid1);

// returned empty

However, I can only use axios respond within the async scope. I cannot use it outside.

What can I do to make it work like it did in nodejs v16?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
webmaster
  • 13
  • 1
  • "*I can only use axios respond within the async scope*" - yes, and that's by design: you need to wait for it. Just put all the code that needs the response inside that scope. – Bergi Feb 06 '23 at 15:13
  • @Bergi — The question is about Node.js support for top-level await. The detour into the IIFE seems to be a distraction from the main point. I don't think the duplicate choice is a good one. – Quentin Feb 06 '23 at 15:57
  • @Quentin Oh, I missed the first sentence I guess. I wonder though what might have changed to make nodejs no longer treat the file as a module? – Bergi Feb 06 '23 at 16:01
  • @Bergi — I think the OP just started a new project and didn't realise there was a difference. – Quentin Feb 06 '23 at 16:02

1 Answers1

0

Node.js still supports top-level await, but (still) only in ECMAScript modules (i.e. not in the default, CommonJS, modules).

To make Node.js recognise the file as an ECMAScript module, either:

  • Add "type": "module" to your package.json file and continue using a .js file extension.
  • Rename the file to have a .mjs file extension

This question covers why your attempted workaround (with an IIFE) failed.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I managed to solved this problem by converting the file extension from .js to .mjs. https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level – webmaster Feb 06 '23 at 19:24