使用 Q Promises 在 node.js 中链接 GET 请求

Using Q Promises to chain GET requests in node.js

我正在尝试将一系列 GET 请求链接在一起。它们是一系列 API 调用,这些调用取决于之前调用的数据。我对 promises 的理解是我应该能够制作一个扁平的 .then() 链,但是当我尝试这样做时,我的 functions/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.

我知道你应该 return 一个承诺,也许我应该 returning deferredGet,但是当我尝试这样做时我没有 return正在处理任何事情。此外,传递给第一个 then 的参数是响应,而不是承诺。所以我不知道从这里去哪里,但我觉得我做错了。

提前致谢!

你是对的,你应该 returning deferredGet。但是,要意识到 returned 仍然是一个承诺。所以你应该在之后继续链接 .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 处理程序中 return 一个承诺时,Q 将使它成为链的一部分。如果您 return 来自处理程序的原始值,Q 将做出一个隐含的承诺,即简单地立即使用该原始值解析,就像您在第一个处理程序中看到的 userAccount 一样。

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