简体   繁体   English

异步/等待 nodejs 支持?

[英]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.我在 Node v8.1.1 上,我尝试使用 async/await 但它不起作用。 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 ? Node 8 版本应该直接支持 Async/await 吧? In the doubt, I tried to run with node --harmony-async-await index.js and node --harmony index.js without result.有疑问,我尝试使用node --harmony-async-await index.jsnode --harmony index.js但没有结果。

async/await is supported by node v8.x. node v8.x 支持 async/await。 However, await has to be inside async function.但是, await 必须在 async 函数中。 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更新:最新的 nodejs 也支持顶级 async/await: 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:我不能说 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()

since it should be clear which block will have async behavior.因为应该清楚哪个块将具有异步行为。 Also for this to work, httpClient.get() should return a Promise .同样为了使其工作, httpClient.get() 应该返回一个Promise Make sure it's so.确保是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM