Node.js 支持异步/等待吗?

10

我遇到一个小问题无法解决。我使用的是 Node v8.1.1 版本,尝试使用 async/await 但是不起作用。我的代码片段看起来像这样:

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}`);
}

当我尝试运行它时,我会收到这个错误消息,然后什么也没有发生:

/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

在Node 8版本中,应该直接支持Async/await,对吗?为了消除疑虑,我尝试使用node --harmony-async-await index.jsnode --harmony index.js运行,但没有结果。


4
await 只能在 async 函数内部使用。 - Felix Kling
它能运行 :) 但是很奇怪 Oo。你知道为什么node不能直接处理从root开始的await使用吗? - mbreton
因为规范不允许。 - Felix Kling
2个回答

12

7

我无法确定node8是否支持async/await,但你可以尝试将try/catch放在一个函数中进行包装,例如:

async function callService() {
    try {
        const resp = await httpClient.get('users?limit=200');
    } catch(e) {
        console.error(`Fail !\n${e}`);
    }
}
callService()

应该清楚哪个块将具有异步行为。此外,为了使其正常工作,httpClient.get() 应该返回一个 Promise。请确保如此。


确实,在提出问题之前我已经进行了检查。 - mbreton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接