gpt4 book ai didi

javascript - 如何在 fetch 中检索对象属性数组,然后将其传递给第二个 fetch 调用?

转载 作者:行者123 更新时间:2023-12-02 22:53:06 26 4
gpt4 key购买 nike

我有一个组件,它依赖于 2 个端点来检索所需程序的名称。我有 2 个端点。第一个端点返回程序列表,它是一个对象数组。目前,它仅返回 4 个节目(2 个节目 ID 为“13”,另外两个节目 ID 为“14”)。第二个端点依赖于这些程序 ID,我需要以某种方式将其传递到第二个端点,避免重复,并用逗号分隔。例如:

第一次获取调用响应:

{
"programs": [
{ "id": 1, "organization": {"organizationId": 2000}, "programId": 13 },
{ "id": 2, "organization": {"organizationId": 2001 }, "programId": 13 },
{ "id": 22, "organization": {"organizationId": 2002 }, "programId": 14 },
{ "id": 20, "organization": {"organizationId": 2000 }, "programId": 14 }
]
}

第二次获取调用:api/v1/program/programlist/13,14

在代码中,这是我到目前为止所做的:

fetch('/api/v1/organizationrelationship/organizationprograms', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => {
if(res) {
_.map(res.programs, (program, index) => {
fetch(`/api/v1/program/programlist/${program.programId}`, { // this is passing all 4 programId individually
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => {
if(res) {
console.log("res: ", res)
}
})
})
}
})

我正在寻找的所需工作流程:

  1. 第一次获取调用成功
  2. 然后进入第二个获取调用
  3. 并在网址中传入programId
  4. api/v1/program/programlist/13,14
  5. 然后我将响应保存在组件的状态中

最佳答案

尝试下面的代码片段,它应该可以解决问题。

fetch('/api/v1/organizationrelationship/organizationprograms', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => {
if(res) {
// gets all the ids from the response and make them a set to remove duplicate
let ids = new Set(res.proprams.map( (program, index) => return program.programId));
// convert the set into and array and the use the toString function to make them comma seperated
let params = Array.from(ids).toString()
fetch(`/api/v1/program/programlist/${params}`, { // this is passing all 4 programId individually
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => {
if(res) {
//here you can now save the response to state
console.log("res: ", res)
}
})
}

})

关于javascript - 如何在 fetch 中检索对象属性数组,然后将其传递给第二个 fetch 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107466/

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