如何连续使用数组中的parms进行api调用



我有一个数组,其中包含一些值,这些值应该作为参数传递给api调用。我想用api调用的结果更新数据。我想每1秒用数组的每个值调用一次api。

示例:

const people = [1, 2, 3, 4, 5];
people.forEach((person, index) => {
setTimeout(() => {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
})
}, index * 1000);
});

由于我想继续调用api并不断更新数据或UI,所以将forEach((封装在无限循环中是个好主意,如下所示:

while(true) {
people.forEach((person, index) => {
setTimeout(() => {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name) ;
})
}, index * 1000);
}) ;
} ;

如果这是一个坏主意,请说明原因并提出其他正确的方法。提前谢谢。

更多信息:-我想使用的api的速率限制为每5秒调用100次api,所以我必须每3秒调用一次,以保持它的实时性而不会达到限制。

每个数组元素都是不同的端点,因此需要完全迭代以保持数据尽可能实时。

该脚本应该全天候运行以更新数据

starwarsapi只是一个例子,因为它是我第一个想到的。

要获得所需的行为,可以使用setInterval(),其间隔时间为people数组的长度。

const people = [1, 2, 3, 4, 5];
setInterval(() => {
people.forEach((person, index) => {
setTimeout(() => {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
})
}, index * 1000);
});
}, people.length * 1000);

但现在你和你的服务器非常健谈,我建议你做一个批量获取,一次获取所有用户,而不是单独获取(你可以更频繁地打电话,让ui尽可能保持最新(。我假设这是你的api,如果你选择的话,你可以添加一个新函数。

const people = [1, 2, 3, 4, 5];
setInterval(() => {
people.forEach((person, index) => {
fetch(`https://swapi.dev/api/people/getList/`, {
method: 'GET',
body: JSON.stringify(people)
})
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
})
});
}, 3000);

这最初是由@Chris G 提供的

这个就像一个魅力

const people = [1, 2, 3, 4, 5];
function apiCall(person) {
fetch(`https://swapi.dev/api/people/${person}/`)
.then(res => res.json())
.then(data => {
// do stuff, eg : update UI
console.log(data.name);
});

}
people.forEach((person, index) => {
setTimeout(() => {
apiCall(person);

setInterval(() => {
apiCall(person);
}, people.length * 1000);

}, index * 1000);
});

因为我花了一些时间来理解上面的代码是如何工作的,所以我将在下面提供一些细节:

forEach循环执行并退出,但在执行时触发了setTimeouts,在运行setTimeouts时触发了setIntervals。所有这些实际上都在forEach循环之外运行,但由于关闭,它们能够访问变量

最新更新