Just a small problem that I can't fix. I'm on Node v8.1.1 and I try to use async/await but it doesn't work. My code snippet looks like this :
const axios = require('axios');
const TOKEN = '...';
const httpClient = axios.create({
baseURL : 'https://myhost/api/',
headers : {
'Authorization': `Token ${TOKEN}`
}
});
try {
const resp = await httpClient.get('users?limit=200');
} catch(e) {
console.error(`Fail !\n${e}`);
}
And when I try to run it, I get this error message and nothing happen :
/Users/mathieu/workspaces/galactic-tools/index.js:13
const resp = await httpClient.get('users?limit=200');
^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Async/await should be supported by Node in version 8 directly, right ?
In the doubt, I tried to run with node --harmony-async-await index.js
and node --harmony index.js
without result.
async/await is supported by node v8.x. However, await has to be inside async function. They always come in pair.
Update: Top level async/await is also supported in the latest nodejs: https://pprathameshmore.medium.com/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478
I can't say if async/await is supported in node8, but you could try wrapping the try/catch in a function like so:
async function callService() {
try {
const resp = await httpClient.get('users?limit=200');
} catch(e) {
console.error(`Fail !\n${e}`);
}
}
callService()
since it should be clear which block will have async behavior. Also for this to work, httpClient.get() should return a Promise
. Make sure it's so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With