【问题标题】:Using Q Promises to chain GET requests in node.js在 node.js 中使用 Q Promises 链接 GET 请求
【发布时间】:2015-06-23 10:05:25
【问题描述】:

我正在尝试将一系列 GET 请求链接在一起。它们是一系列 API 调用,依赖于先前调用的数据。我对 Promise 的理解是我应该能够创建一个扁平的 .then() 链,但是当我尝试这样做时,我的函数/console.logs 没有按正确的顺序执行,所以我现在有一个不断增长的金字塔厄运:

var request = require('request');
var deferredGet = Q.nfbind(request);

deferredGet(*params*)
  .then(function(response){
  // process data from body and add it to the userAccount object which I am modifying.
    return userAccount;
  })
  .then(function(userAccount){
    deferredGet(*params*)
      .then(function(response){
        //process data from body and add to userAccount
        return userAccount;
    })
    .then(function..... // There's a total of 7 API calls I need to chain, and it's already getting unwieldy.

我知道你应该返回一个承诺,也许我应该返回deferredGet,但是当我尝试这样做时,我没有返回任何东西。此外,传递给第一个 then 的参数是响应,而不是承诺。所以我不知道从哪里开始,但我觉得我做错了。

提前致谢!

【问题讨论】:

  • 这绝对是 不是 Benjamin Gruenbaum 链接的问题的副本,尽管它是相关的并且可能会有所帮助。
  • 这个 is 重复了,他问的问题与我在那儿问问题时的意思完全相同,但缺少同一点。我给了你的(好)答案一个赞成票,欢迎你在那里添加一个答案 - 但这种链接能力是这两个问题的意义所在。
  • 乍得:你用的是什么版本的node/io.js?
  • 我启动并运行了它,我对 Promise 的功能有一个基本的误解,更详细的示例有助于解决这个问题。非常感谢您和 Alex 的宝贵时间!

标签: javascript node.js promise q


【解决方案1】:

您是正确的,您应该返回deferredGet。但是,要意识到返回的仍然是一个承诺。所以你应该在之后继续链接.then 调用。

var request = require('request');
var deferredGet = Q.nfbind(request);

deferredGet(*params*)
  .then(function(response){
    // process data from body and add it to the userAccount object which I am modifying.
    return userAccount;
  })
  .then(function(userAccount){
    return deferredGet(*params*);
  })
  .then(function(response){
    // response should be the resolved value of the promise returned in the handler above.
    return userAccount;
  })
  .then(function (userAccount) {
    //...
  });

当您从 then 处理程序中返回一个承诺时,Q 将使它成为链的一部分。如果您从处理程序返回原始值,Q 将做出一个隐含的承诺,该承诺会立即使用该原始值解析,正如您在第一个处理程序中看到的 userAccount

查看this working example我为你整理的:)

【讨论】:

  • 谢谢你,这帮助很大。我遵循承诺的想法,我只需要一个更充实的例子。我的代码现在已经启动并运行了,而且不那么丑陋了!
猜你喜欢
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 2021-09-07
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多