我有一些通过网络调用不断更新一系列对象的代码,如下所示。我想知道这是不是不好的做法,是否有更好的办法。我不能使用set interval,因为MakeAsyncCall
回复之间的时间是可变的,如果打电话的时间长于延迟,则可能导致泄漏。我将使用此信息更新用户界面。这会引起阻塞吗?你是怎么想的?如果你需要更多的信息请告诉我。
let group = [item1, item2, item3];
// Start Loop
readForever(group, 100);
// Function to Delay X ms
const delay = ms => {
return new Promise((resolve, _) => {
const timeout = setTimeout(() => {
resolve();
}, ms);
});
};
// Function to continuously Make Calls
const readForever = async (group, ms) => {
while(true) {
// Make Async Call
for (let item of group) {
await MakeAsyncCall(item);
}
// Wait X ms Before Processing Continues
await delay(ms);
}
};
最佳答案
给定的代码不会导致任何ui阻塞。是一种持续更新用户界面的有效方法。
你可以这样写而不是循环:
const readForever = async (group, ms) => {
// Make Async Call
for (let item of group) {
await MakeAsyncCall(item);
}
// Wait X ms Before Processing Continues
await delay(ms);
if (true) { // not needed, but there you could define an end condition
return readForever(group, ms);
}
};
除了关于
delay
函数的注释之外:您可以直接将
resolve
传递给setTimeout
,并且因为您不需要在任何地方取消超时,所以您不需要将结果setTimeout
存储在变量中。const delay = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};