Search code examples
javascriptwhile-loopeslint

How to fix ESLint errors 'no-loop-func' and 'no-await-in-loop' in while loop


This code gets child TreeNodes from depth by parent, until you get the first level node. How to fix ESLint errors with 'no-loop-func' and 'no-await-in-loop', without supressions and changing rules. Didn't find any examples for while loop.

    const nodes = await loadNodeList();
    let buffNodes = [];
    let buff = {};    
    
    buff = await loadNodeById(id);
    
    while (!nodes.find((elm) => elm.id === buff.id)) { // Function declared in a loop contains unsafe references to variable(s) 'buff'.(no-loop-func)
      buff = await loadNodeById(buff.parent.id); // Unexpected `await` inside a loop.(no-await-in-loop)
      buffNodes.push(buff);
    }

Solution

  • Check this out https://eslint.org/docs/latest/rules/no-await-in-loop

    Fast answer

    /* eslint-disable no-await-in-loop */
    for (let i = 0; i <= 10; i += 1) {
      const res = await DoSomething();
    }
    /* eslint-enable no-await-in-loop */
    

    Also, you can try to use for await of ...

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of