如何在 axios return 中迭代每个循环中的新百分比+数组

How to iterate in axios return the new percentage + array in every loop

问题

我还在习惯函数式编程 (FP)。特别是 React-native 中的 FP。目标是:

尝试

为每个步骤创建单独的函数是可以的,问题是如何 'connect' 它们并获得所需的结果(如 'The Problem' 部分所述)。我尝试的每个想法都导致某种类型的耦合或重复(代码)

请求

function requestCharacters(start, token) {
  return axios.get(`https://swapi.dev/api/people/${start}/`,{
           headers: {
             Authorization: 'Bearer ' + token,
             ContentType: 'application/json',
           }
         })
}

function requestPlanets(start) {
  return axios.get(`https://swapi.dev/api/planets/${start}/`);
}

百分比

const percentage = Math.round((start/finish)*100)

请求的迭代(使用递归)

  async function loop(start, finish, callback) {
      if (start >= finish) {
        console.log("got inside if from loop");
        return;
      }
    
      await requestCharacters(1)
        .then((response) => {
          const percentage = Math.round(((start)/finish)*100)
          loop(start + 1, finish, callback({ percentage, pageContent: response.data });
        })
        .catch((error) => console.error(error));
    }
    
loop(1, 3, console.log(percentage, pageContent));

然后一些函数返回百分比加上object fechted

loop(1, 3, PrintObjectsFromFetch)

如何解决?

谢谢你看完了!

这是未重构的版本。希望对你有帮助

import axios from "axios";

function mountAxiosRequest(url) {
  return axios.get(url);
}
const arrayOfPages = (total_pages, baseURL) =>
  Array.from({ length: total_pages }, (v, k) =>
    baseURL.replace("iterator", k + 1)
  );

const total_pages = 16;
const baseURL = "https://swapi.dev/api/people/iterator/";
const arrayOfRequests = (total_pages, baseURL, request) =>
  arrayOfPages(total_pages, baseURL).map((url) => request(url));

function PrintPercentageAndData(data) {
  console.log("from map percentage: ", data);
}

const mapResponses = (response, total) =>
  response.map((row, index) => {
    const indexFromOne = index + 1;
    const percentage = Math.round((indexFromOne / total) * 100);
    return { percentage, data: row };
  });

const promiseArray = (arrayOfRequests) => Promise.all(arrayOfRequests);

function GetPercentageAndData(callback, baseURL, request) {
  const total_pages = 10;
  const requestsArray = arrayOfRequests(total_pages, baseURL, request);
  const promissesArray = promiseArray(requestsArray);
  promissesArray
    .then((results) => {
      const result = PrintPercentageAndData(
        mapResponses(results, results.length)
      );
      if (result !== undefined) callback(result);
    })
    .catch((error) => console.error("error from promissesArray : ", error));
}
GetPercentageAndData(
  PrintPercentageAndData,
  "https://swapi.dev/api/species/iterator/",
  mountAxiosRequest
);