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

rok*_*rok 2 javascript es6-promise

我有以下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));
  });
Run Code Online (Sandbox Code Playgroud)

然后在另一个文件中调用此函数:

getContacts(token)
.then((data) => {
  const contacts = data.data;
  console.log(contacts);
})
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

当从API返回的数据量较大时,将对其进行分页。响应中包含一个链接,需要获取该链接才能获取下一页。我希望我的代码首先遍历所有页面并收集所有数据,然后解决承诺。当执行到达该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));
  });
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

首先,已经返回promise的情况下不要使用new Promise构造函数fetch

然后,只需使用递归方法并将您的诺言与then

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);
  });
}
Run Code Online (Sandbox Code Playgroud)