2016-09-20 25 views
0

您好,我試圖讓Unirest返回一個承諾,以便我可以創建一個函數,從外部進程調用它並將響應返回給調用進程。但是,我無法弄清楚如何獲得回覆的答覆。返回來自Unirest客戶端的承諾

這是我到目前爲止有:

const unirest = require('unirest'); 

function auth() { 
    yield unirest.post('https://xxx.xxx.xxx.xxx/authorize/') 
     .headers({'Accept': 'application/json', 'Content-Type': 'application/json'}) 
     .send({"Username": "user1", "Password": "password"}) 
     .end().exec(); 
} 
auth() 

然而,這將引發以下錯誤:

yield unirest.post('https://xxx.xxx.xxx.xxx/authorize/') 
     ^^^^^^^ 
SyntaxError: Unexpected identifier 
    at Object.exports.runInThisContext (vm.js:76:16) 
    at Module._compile (module.js:528:28) 
    at Object.Module._extensions..js (module.js:565:10) 
    at Module.load (module.js:473:32) 
    at tryModuleLoad (module.js:432:12) 
    at Function.Module._load (module.js:424:3) 
    at Module.runMain (module.js:590:10) 
    at run (bootstrap_node.js:394:7) 
    at startup (bootstrap_node.js:149:9) 
    at bootstrap_node.js:509:3 
+0

爲什麼要屈服而不是返回?這看起來不像一個發電機, –

+0

我是按照這裏提出的建議:https://github.com/Mashape/unirest-nodejs/pull/60 – user1513388

+0

該問題仍然是開放的,你確定是不直接甚至返回一個承諾在此刻?該變化似乎還沒有被應用。 –

回答

0

你不做出承諾一些回報,但可以從回報的承諾你的功能將會滿足結果。由於.exec()給你的承諾已經,你可以return它:

function auth() { 
    return unirest.post('https://xxx.xxx.xxx.xxx/authorize/') 
     .headers({'Accept': 'application/json', 'Content-Type': 'application/json'}) 
     .send({"Username": "user1", "Password": "password"}) 
     .end().exec(); 
} 
auth().then(console.log); 

我不知道爲什麼你想yield什麼。承諾應使用async functions(提案ES8),在其中您可以使用await並總是返回一個承諾異步結果implictly消耗:

async function auth() { 
    const val = await unirest.post('https://xxx.xxx.xxx.xxx/authorize/') 
     .headers({'Accept': 'application/json', 'Content-Type': 'application/json'}) 
     .send({"Username": "user1", "Password": "password"}) 
     .end().exec(); 
    return val; 
} 
auth().then(console.log); 

但是這是在你的情況是不必要的,因爲你不對價值做任何事情,所以你可以退回承諾範圍。

it throws the following error SyntaxError: Unexpected identifier

你試圖使用yield運營商在沒有標記爲發電機功能的功能。通過使用諸如co等專用運行庫,可以使用使用promise作爲異步/等待的polyfill的生成器。你的代碼看起來像這樣:

function* auth() { 
// ^
    const val = yield unirest.post('https://xxx.xxx.xxx.xxx/authorize/') 
     .headers({'Accept': 'application/json', 'Content-Type': 'application/json'}) 
     .send({"Username": "user1", "Password": "password"}) 
     .end().exec(); 
    return val; 
} 
co(auth()).then(console.log);