gpt4 book ai didi

javascript - 在 JS promise 函数中遍历 API 响应的多个页面

转载 作者:行者123 更新时间:2023-11-29 16:38:59 25 4
gpt4 key购买 nike

我有以下 promise 函数,它使用 fetch 从 API 获取数据:

const getContacts = token =>
new Promise((resolve, reject) => {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then((data) => {
resolve(data);
})
.catch(err => reject(err));
});

然后在不同的文件中调用此函数:

getContacts(token)
.then((data) => {
const contacts = data.data;
console.log(contacts);
})
.catch(err => console.error(err));

当API返回的数据量较大时,会进行分页。响应包含一个链接,需要获取该链接才能获取下一页。我希望我的代码首先遍历所有页面并收集所有数据,然后解决 promise 。当执行到 const contacts = data.data 行时,它应该有来自每一页的数据(目前它只返回第一页)。

实现此目标的最佳方法是什么?

编辑:

我在 getContacts 函数中尝试了递归。这样我就可以遍历所有页面并获取一个对象中的所有数据,但我不知道将其解析回最初调用该函数的代码的正确方法是什么。下面的代码无法正确解析。

const getContacts = (token, allData, startFrom) =>
new Promise((resolve, reject) => {
if (startFrom) {
url = `${url}?${startFrom}`; // the api returns a set of results starting at startFrom (this is an id)
}
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then((data) => {
let nextPageExists = false;
Object.assign(allData, data.data);

data.links.forEach((link) => {
if (link.rel === 'next') {
nextPageExists = true;
getContacts(token, allData, link.uri);
}
});
if (!nextPageExists) {
resolve({ data: allData });
}
})
.catch(err => reject(err));
});

最佳答案

首先,do not use the new Promise constructor when fetch already returns a promise .

然后,只需使用递归方法并使用 then 链接您的 promise:

function getContacts(token, allData, startFrom) {
return fetch(startFrom ? url + '?' + startFrom : url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then(response => response.json()).then(data => {
Object.assign(allData, data.data);
const nextPage = data.links.find(link => link.rel === 'next');
if (!nextPage)
return allData;
else
return getContacts(token, allData, nextPage.uri);
});
}

关于javascript - 在 JS promise 函数中遍历 API 响应的多个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48302361/

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