gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:17:35 24 4
gpt4 key购买 nike

我正在尝试将一系列 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.

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

提前致谢!

最佳答案

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

查看 this working example我为你准备好了:)

关于javascript - 在 node.js 中使用 Q Promises 链接 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com