Home > database >  Looping through array and update variable based on async code [closed]
Looping through array and update variable based on async code [closed]

Time:09-28

I am trying to loop through an array and calling a promise, and based on that result it updates the variable. The code is working as I wanted but I am concerned if this is a good way to write it. Are there any better ways? Thank you in advance.

/**
*
* u/returns Resolves a promise and returns value 'b'
*/
async function generatePromise() {
   return Promise.resolve('b');
}

async function main() {
   let showWarning = false;
   // List of users
   const users = ['a', 'b', 'c'];
   //Looping through users array and compare the result from promise and update showWarning boolean
   await users.reduce(async (promise, user) => {
     await promise;
     const result = await generatePromise();
     if (result === user) showWarning = true;
   }, Promise.resolve())

   console.log(showWarning)
}
main();

CodePudding user response:

Seems unnecessarily complicated and the logic is somewhat backwards. Assuming that generatePromise will always return the same response, why would you call it multiple times? Call it once and check whether the value is contained in the array:

const showWarning = users.includes(await generatePromise());

If the function needs to be called multiple times (e.g. because it could potentially return a different response per input/user) then you can use a simple for loop:

for (const user of users) {
  if (user === await generatePromise()) {
    showWarning = true;
    break; // why check other users if `showWarning` won't change anymore?
  }
}
  • Related