简体   繁体   English

Axios:如何一个接一个地运行多个请求?

[英]Axios : How to run multiple requests one after the other?

I have a very large array of IDs (thousands of IDs).我有一个非常大的 ID 数组(数千个 ID)。 I want to loop through this array and for each value, make a request to an API like so:我想遍历这个数组,并为每个值,向 API 发出请求,如下所示:

[12, 32, 657, 1, 67, ...].forEach((id) => {
    axios.get(`myapi.com/user/${id}`).then(({ data }) => {
        console.log(data.name);
    });
});

However, I have so many requests to make I can't make them asynchronous because my computer has limits... Is it possible to wait for each request to be finished before making the next one?但是,我有很多请求要发出,我无法使它们异步,因为我的计算机有限制……是否可以等待每个请求完成后再发出下一个请求?

Instead of using forEach in id try Promise.all而不是在 id 中使用forEach尝试Promise.all

const ids = [12, 32, 657, 1, 67];
const promises = ids.map((id) => axios.get(`myapi.com/user/${id}`));

Promise.all([...promises]).then(function (values) {
  console.log(values);
});

Let's say we want many promises to execute in parallel and wait until all of them are ready.假设我们希望许多 Promise 并行执行并等待它们都准备好。

For instance, download several URLs in parallel and process the content once they are all done.例如,并行下载多个 URL 并在完成后处理内容。

From https://javascript.info/promise-api来自https://javascript.info/promise-api

Firstly, it's clear you have to redesign your api.首先,很明显你必须重新设计你的 api。

However, you can try:但是,您可以尝试:


Promise.all([12, 32, 657, 1, 67, ...].map((id) => {
    return axios.get(`myapi.com/user/${id}`).then(({ data }) => {
        console.log(data.name);
    });
})).then(_=>console.log('done'));

or look into p-queue which will help you manage the queue of promises.或查看p-queue ,它将帮助您管理承诺队列。

Let's assume that you allow n requests to be sent maximum at any given time.假设您允许在任何给定时间最多发送n请求。 For the sake of the example I assume it's 10:为了这个例子,我假设它是 10:

var n = 10;

We also store the current index:我们还存储当前索引:

var index = 0;

Let's implement a function to handle the requests:让我们实现一个 function 来处理请求:

function req() {
    axios.get(`myapi.com/user/${input[index]}`).then(({ data }) => {
        console.log(data.name);
        if (index + 1 < input.length) {
            index++;
            req();
        }
    });    
}

Then, let's send the first n requests:然后,让我们发送前n请求:

while (index < n) {req(); index++}

Yes, index is global, but it is global for the sake of readability.是的, index是全局的,但为了可读性,它是全局的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM