2017-06-14 230 views
1

只是一個我無法修復的小問題。我在Node v8.1.1上,我嘗試使用async/await,但它不起作用。我的代碼片段看起來是這樣的:異步/等待nodejs支持?

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 

異步/伺機應該由節點版本8中的直接支持, 對 ? 如有疑問,我試圖用node --harmony-async-await index.jsnode --harmony index.js運行而沒有結果。

+3

'await'只在'async'函數內有效。 –

+0

它工作:)但它很奇怪Oo。你知道爲什麼node不能直接從root處理'await'用法嗎? – mbreton

+0

因爲規範不允許。 –

回答

3

我不能說,如果異步地等待着node8是扶持產品/,但你可以嘗試包裹的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。確保它是如此。

+4

http://node.green/可以告訴你它是否可用;) –

+0

確實,我查詢之前問這個問題 – mbreton

0

節點v8.x支持async/await。但是,等待必須在內部的異步功能。他們總是成對的。