简体   繁体   English

在ASYNC AWAIT内部的While循环

[英]While Loop inside ASYNC AWAIT

I have some code that continuously updates a series of objects via network calls looks like this. 我有一些代码可以通过网络调用不断更新一系列对象,如下所示。 I was wondering if this is bad practice and if there might be a better way. 我想知道这是否是不好的做法,是否有更好的方法。 I cant use Set Interval as the time between MakeAsyncCall replies is variable and can cause a leak if the time to make the call is longer than the delay. 我无法使用Set Interval,因为MakeAsyncCall回复之间的时间是可变的,并且如果进行呼叫的时间长于延迟,则可能导致泄漏。 I will be using this info to update a UI. 我将使用此信息来更新UI。 Will this cause blocking? 这会导致阻塞吗? What are your thoughts? 你怎么看? Let me know if you need more info. 让我知道您是否需要更多信息。

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);
    }
};

The given code won't cause any UI blocking. 给定的代码不会导致任何UI阻塞。 And is a valid way to update the UI continually. 这是连续更新UI的有效方法。

Instead of a loop you could write it that way: 代替循环,您可以这样写:

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);
  }
};

In addition to the comment about the delay function: 除了有关delay功能的注释:
You could directly pass the resolve to setTimeout , and because you do not cancel the Timeout anywhere you do not need to store the result setTimeout in a variable. 你可以直接通过resolvesetTimeout ,因为你不会在任何地方取消超时,你不需要把结果存储setTimeout一个变量。

const delay = ms => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

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

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