0

I am trying to loop an array and delay the loop if the request is still processing and continue the loop when the request is done.

Here is what my codes look like

// request is from redux
for (var i = 0; i < request.length; i++) {
    let k = i;
    setTimeout(function () {
        // requestInProgress came from redux so it will re-render when the value is updated
        if(!requestInProgress){
            // proceed the loop
        } else {
            // I want to delay the loop by giving more timeout but not sure how it should be done here
        }
    }, 5000 * (k + 1));
}

Currently, I don't have anything in else statement. I just thought of adding more time delay there but not sure if it can be done that way. Any help would be much appreciated. Thank you.

Emerald
  • 864
  • 1
  • 14
  • 37
  • 2
    I don't think you'll get the updated value of `requestInProgress` in your loop. When your loop begins, `requestInProgress` has a value, probably either `true` or `false`. It will remain that value for the rest of your loop. – David Heisnam Dec 13 '21 at 13:33
  • I see. I didn't know about that. Do you have any suggestion on what structure should I apply that execute similar to that method which can read the new value update from redux? – Emerald Dec 13 '21 at 13:52
  • 1
    Read this, it is not exact solution for you but will help you - https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Gaurav Dec 13 '21 at 15:36
  • Are you using React Hooks or Class based components? – David Heisnam Dec 13 '21 at 20:11

1 Answers1

0

If you are trying to wait for your request before running the code, you could try using async await. Though I don't how requestInProgress is being passed on your code.

  const get_data = async () => {
    const response = await fetch('http://your-request')
    console.log(`code after request, response: ${response}`)
    //code here
  }
paoloml
  • 19
  • 1
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 13 '21 at 15:33