gpt4 book ai didi

javascript - While 循环在 .then() 异步中

转载 作者:行者123 更新时间:2023-11-28 16:52:15 24 4
gpt4 key购买 nike

我最近遇到了一个有趣的问题,我一生都无法解决。我正在调用一个 API 调用,该调用将记录分解为页面,页面的信息驻留在响应 header 中。由此,我希望能够进行另一次调用来检索数据和下一个 header ,直到不再有响应 header 。

let parents = {};

const options = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(
`/api/v1/courses/200003/enrollments?enrollment_type=ObserverEnrollment&per_page=100`,
options
).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
parents = res;

nextURL(res.headers.get("Link"));

let optionsNext = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(nextURL(res.headers.get("Link")), optionsNext).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
if (res.ok) {
parents.data.push(res.data);
console.info(parents);
}
})
);
})
);

function nextURL(linkTxt) {
let url = null;
if (linkTxt) {
let links = linkTxt.split(",");
let nextRegEx = new RegExp('^<(.*)>; rel="next"$');

for (let i = 0; i < links.length; i++) {
let matches = nextRegEx.exec(links[i]);
if (matches) {
url = matches[1];
}
}
}
return url;
}

我需要放入某种循环中的部分是基于 nextURL 函数的返回的二次获取:if !nextURL(res.headers.get("Link"))我需要打破循环。

let optionsNext = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
fetch(nextURL(res.headers.get("Link")), optionsNext).then(response =>
response
.json()
.then(data => ({
data: data,
ok: response.ok,
headers: response.headers
}))
.then(res => {
if (res.ok) {
parents.data.push(res.data);
console.info(parents);
}
})
);

预先感谢您关注我的可怜问题

最佳答案

尝试使用递归;像这样的东西:

const getFetcher = () => ({
aggregate: [],
run: function (url, options) {
return new Promise((resolve, reject) => {

fetch(url, options)
.then(response => {
const json = response.json();
const { headers, data } = response;
const nextLink = res.headers.get("Link");
this.aggregate.push(data);
if (nextLink) {
this.run(nextLink, options).then(resolve);
}
else {
resolve(this.aggregate);
}
})

})
}
})
const options = {
credentials: "same-origin",
headers: {
accept: "application/json"
},
timeout: 5000
};
const fetcher = getFetcher();
fetcher.run(`/api/v1/courses/200003/enrollments?enrollment_type=ObserverEnrollment&per_page=100`, options)
.then(allPagesData => {
/* at this point you have all the pages data */
})

关于javascript - While 循环在 .then() 异步中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773306/

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