javascript 如何按顺序获取N个请求[已关闭]

gr8qqesn  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(85)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
昨天关门了。
Improve this question
假设我请求一个url,它返回最大页数,即5。然后我需要请求第2页,第3页,第4页和第5页。
然而,为了不被阻塞,这些不能同时完成,而是顺序完成,所以Promise.all()不会工作(如果我理解正确的话)。
如果我事先知道我必须获得多少页面,我可以只链.then s,但我只在第一次请求后获得信息。
来自所有请求的数据也必须被收集、处理并传递给另一个函数。
我怀疑这与承诺有关,但如何正确地将它们联系起来,我无能为力。

3qpi33ja

3qpi33ja1#

您可以通过定义Promise.resolve()并在每次迭代中链接它来顺序地获取请求。

let urls = [];
Array(21).fill('').forEach((_,i)=>{
  urls.push('https://dummyjson.com/carts/'+(i+1));
});

let promise = Promise.resolve();
console.time('time execution');
urls.forEach((url,i) => {
  promise = promise.then(() => 
    fetch(url)
    .then(r => r.json())
    .then(r => console.log(r))
    .catch(e => console.error(e))
    .finally(() => {
      if(i === urls.length - 1) console.timeEnd('time execution');
    }) 
  );
});

另一种方式:使用异步等待

let urls = [];
Array(21).fill('').forEach((_,i)=>{
  urls.push('https://dummyjson.com/carts/'+(i+1));
});

(async () => {
  console.time('time execution')
  for(let [i,url] of urls.entries()) {
    console.log(await new Promise((resolve, reject) => {
      fetch(url)
      .then(r => r.json())
      .then(r => resolve(r))
      .catch(e => reject(e))
      .finally(() => {
        if(i === urls.length - 1) console.timeEnd('time execution');
      });
    }));
  }
})();
bsxbgnwa

bsxbgnwa2#

您可以使用类似p-limit的工具手动执行此操作
示例:

import pLimit from 'p-limit';

const limit = pLimit(1);

async function getData(x: number) {
  // do whatever you neeed aasynchronously here
  return x;
}

async function otherFunction() {
  // some input parameters for the async getData function:
  const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  // set concurrency limit to 5:
  const limit = pLimit(5);

  // run Promite.all on the closures processed by your `limit`
  return Promise.all(input.map(e => limit(() => getData(e))));
}

相关问题