从Unirest客户那里回复承诺

时间:2016-09-20 21:50:00

标签: javascript node.js promise unirest

您好我正在尝试让Unirest返回一个promise,以便我可以创建一个函数,从外部进程调用它并将响应返回给调用进程。但是,我无法弄清楚如何获得返回响应的承诺。

这是我到目前为止所做的:

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

1 个答案:

答案 0 :(得分:1)

你没有做出承诺返回的东西,但你可以从你的函数中返回将满足结果的承诺。由于.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提案)来使用Promise,您可以在其中使用await,并且将始终隐含地返回异步结果的承诺:

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

然而,在你的情况下这是不必要的,因为你没有对价值做任何事情,所以你可以将承诺拉回来。

  

它会抛出以下错误SyntaxError: Unexpected identifier

您试图在未标记为生成器函数的函数中使用yield运算符。通过使用co等专用的运行库,可以使用使用promises作为async / await的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);