Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await nodejs support?

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.

like image 835
mbreton Avatar asked Jun 14 '17 12:06

mbreton


2 Answers

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

like image 181
Comtaler Avatar answered Sep 20 '22 13:09

Comtaler


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.

like image 25
John Smith Avatar answered Sep 21 '22 13:09

John Smith