mbr*_*ton 8 javascript asynchronous node.js async-await
只是一个我无法解决的小问题.我在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}`);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行它时,我收到此错误消息,没有任何反应:
/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
Run Code Online (Sandbox Code Playgroud)
版本8中的Node应该直接支持Async/await,对吧?在怀疑,我试图与运行node --harmony-async-await index.js,并node --harmony index.js没有结果.
我不能说在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()
Run Code Online (Sandbox Code Playgroud)
因为应该清楚哪个块将具有异步行为.同样为了这个工作,httpClient.get()应该返回一个Promise.确保它是这样的.
| 归档时间: |
|
| 查看次数: |
4555 次 |
| 最近记录: |