简体   繁体   中英

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. I will be using this info to update a 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. And is a valid way to update the UI continually.

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:
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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