Promise with setTimeout 不会 return json

Promise with setTimeout doesn't return json

由于电影数据库 API 限制(每 10 秒 40 个请求)我正在请求 api 的数据,冷却时间为 4 秒。所以,我需要等待 4 秒,直到解决下一个承诺。

我知道我必须将 setTimeout 包装在 Promise 中,但如何将响应 url 转换为 json?

我不成功的做法:

const pages_Array = [1, 2, 3, 4, 5];

let getSearchResultsForOnePage = url => {
  //fetch
  return fetch(url);
};

let pause = time => {
  // handy pause function to await
  return new Promise(resolve => setTimeout(resolve, time));
};

let getAllSearchResultProfiles = async searchURL => {
  let URLs = [];
  for (let i = 0; i < pages_Array.length; i++) {
    URLs.push(searchURL + pages_Array[i]);
  }
  console.log(URLs);
  let responses = [];
  for (url of URLs) {
    console.log("sending request");
    response = await getSearchResultsForOnePage(url);
    console.log("received", response);
    console.log(typeof response)
    responses.push(response);
    await pause(4000);
  }

  return responses;
};

let getAllIDs = () => {
  getAllSearchResultProfiles(mainURL).then(response => {
    data = response.json();
    console.log(data);
  });
};

getAllIDs();

函数 getAllSearchResultProfiles 解析为 responses 数组。稍后,您尝试对这个数组执行 .json(),但这不起作用;您必须对数组中的每个单独项目执行 .json() 。这可能看起来像这样:

getAllSearchResultProfiles(mainURL).then(responses => {
  const jsonBodies = responses.map(response => response.json());
});

但由于 .json() 本身 returns 是一个承诺(即一旦接收到完整的 HTTP 正文并将其解析为 JSON 就会解​​析的承诺),您可以改为使用 .json() 从你的 getAllSearchResultProfiles 函数中。 (否则,您必须使用 Promise.all。)

因此,与其在 for 循环中执行 responses.push(response),不如执行 responses.push(await response.json())。这样 JSON 响应被直接推入 responses 数组,您将能够在 .then():

中按原样使用它
getAllSearchResultProfiles(mainURL).then(data => {
  console.log(data);
});