javascript - 在 Sails 中使用多个 unirest 请求

标签 javascript node.js sails.js

我有以下代码

index: function (req, res) {

  var Request = unirest.get("https://poker.p.mashape.com/index.php?players=4").headers({ "X-Mashape-Authorization": "xxxxxxxxxxxxxxxxx" }).end(function (response) {
    players = response.body;

    showdown_total = players.showdown.length;
    showdown = Array();


  });
  console.log(players);

  // Send a JSON response
  res.view({
    hello: 'world',
    //players: players
  });

},

如果我在 unirest get 中添加 res.view 效果很好,但我想将这些变量发送到 view 并被能够添加另一个 unirest 请求

感谢您的帮助

最佳答案

就是这样asynchronous code在 Node.js 中工作。

基本上,当一个操作没有尽快评估时, Node 不会等待它。它只是说,“好吧,不用担心,完成后告诉我”.. 有点。

问题是,在您的代码中,您没有告诉 Node 您的获取请求。已经完成了。您只需在请求函数开始考虑获取数据之前将 View 发送给客户端即可。

如何让 Node 等待?

你有一些选择。要么给它一个回调函数(完成后执行此操作),要么必须嵌套函数。这两者实际上是同一件事。

我将向您展示一种解决方案,嵌套函数:

var urlOne = "https://poker.p.mashape.com/index.php?players=4",
    urlTwo = "http://some.other.url",
    headers = { "X-Mashape-Authorization": "xxxxxxxxxxxxxxxxx" };

// Run first request
unirest.get(urlOne).headers(headers).end(function (response) {
    players = response.body;
    showdown_total = players.showdown.length;
    showdown = Array();

    // Run second request
    unirest.get(urlTwo).headers(headers).end(function (response) {
        someVar = response.body;

        // Show all my data to the client
        res.view({
            players: players,
            someOther: someVar
        });
    });
});

其他解决方案:

  • 如果您不想嵌套函数,请给它们一个回调,以便在函数完成时运行。
  • 使用模块来处理异步代码,例如 one of the more popular ones称为异步

我建议您在直接跳到外部库之前阅读更多有关回调、异步代码和 Nodejs 的内容。

关于javascript - 在 Sails 中使用多个 unirest 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23304883/

相关文章:

node.js - 我对 Sails.js 水线一对一关联逻辑感到困惑

javascript - 删除mongodb数据库中的数组字段

javascript - 从链接点击中捕获 ID 并将其传递到弹出表单中

javascript - 如何在启动 Flex 应用程序时禁用浏览器的最小化按钮?

javascript - PSQL : error: relation does not exist

node.js - ExpressJS只接受6次POST?

javascript - 大多数中间件(如 compress)不再与 Express 捆绑在一起

javascript - 滚动时使第二个容器粘在第一个容器之后的右上方

javascript - 如何修复 Firebug 上显示的 "return not in function"错误?

javascript - 如何防止在 EJS 中多次打印?