所以,我目前正在从一个API中提取,它给出了这样的响应。
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 10
},
"objects": [
{
"date": "2019-03-15",
"id": 16,
"mSlug": "gud_vs_dex",
"resource_uri": "/api/v1/match/16/",
"team1": "/api/v1/team/7/",
"team2": "/api/v1/team/3/",
"time": "21:30:00",
"viewLink": "twitch.tv/tectalparrot198q",
"viewLink2": null
},
然后,我需要能够从该响应中获得5个字段- mSlug
、team1
、team2
、date
和time
。我可以轻松获得mSlug
、date
和time
。然而,问题是我需要使用从team1
和team2
返回的链接来发出新的GET请求,这些请求返回的API如下所示:
{
"captain": "Parrayeet",
"currentRanking": 100,
"id": 7,
"members": "CFE SilentHeart,GreenTigerBeast,Pack Jaul",
"name": "Guardian Down",
"platform": "Xbox",
"resource_uri": "/api/v1/team/7/",
"slug": "guardian_down"
}
从这里,我需要能够获得我正在搜索的团队的名称。最后,我需要能够将所有调用的信息拼凑在一起,使一个字符串告诉用户团队的名称(来自第二次/第三次调用),以及第一次调用的日期/时间/链接。但是,因为请求是异步的,所以我无法将这些结果保存到任何变量或数组中,因此我不能简单地执行
slug = response.body.objects[0].mSlug
有没有什么好方法可以让我发出多个GET请求,其中一些使用响应的信息,并在结束时将数据连接在一起?我尝试过使用fetch
、request
和request-promise
,但都没有用。任何帮助(以及解释为什么这样做)都会有所帮助。
发布于 2019-03-20 08:59:41
你可以像这样链接你的承诺:
rp(options)
.then(function (body) {
idk(body.objects)
return body
})
.then(function (value) {
// do something with value
makeCall(value.objects)
idk(body.objects)
})
.catch(function (err) {
console.log(err)
});
在您的第一个promise解析之后,您可以使用return将值传递给下一个.then方法。
发布于 2019-03-20 09:40:55
也许这一点更清楚。因为我从makeCall函数返回了一个promise,所以您可以访问.then方法。
makeCall(options).then(res => {
options = {
url = "yourendpoint.com" + res.objects[0].team1;
}
makeCall(options).then(res => {
console.log(res)
})
options = {
url = "yourendpoint.com" + res.objects[0].team2;
}
makeCall(options).then(res => {
console.log(res)
})
})
function makeCall(options) {
return rp(options)
.then(function (body) {
return Body
})
.catch(function (err) {
console.log(err)
});
}
或者,您可以在异步函数中等待承诺解析,如下所示:
call();
call = async () => {
// some logic
let res = await makeCall(options);
// do something with response
// create new options
let req = await makeCall(options);
}
function makeCall(options) {
return rp(options)
.then(function (body) {
return body
})
.catch(function (err) {
return err
});
}
https://stackoverflow.com/questions/55251987
复制相似问题