【问题标题】:Returning a promise from the Unirest client从 Unirest 客户端返回一个承诺
【发布时间】:2016-09-20 21:49:59
【问题描述】:

您好,我正在尝试让 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

【问题讨论】:

  • 为什么收益而不是回报?看起来不像发电机,
  • 我遵循这里提出的建议:github.com/Mashape/unirest-nodejs/pull/60
  • 那个问题仍然存在,你确定 unirest 甚至在这一点上返回了一个承诺吗?该更改似乎尚未应用。
  • 嗯。好吧,也许它没有,我误读了这个问题。我想我需要在这种情况下寻找替代方案。

标签: javascript node.js promise unirest


【解决方案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 任何东西。 Promise 应该使用 async functions(ES8 提案)来使用,您可以在其中使用 await 并且总是隐含地返回异步结果的 Promise:

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),可以使用将 Promise 用作 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);

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2020-06-09
    相关资源
    最近更新 更多