how to implement promise.allSettled in Javascript

I have this code to search if a user is in the list or not. The thing is, I need to implement the calls to findOne in parallel. How can I add the promise.allSettled?

As is the code, how can I create multiple calls to findOne? I have reviewed the documentation of the Promises but I don’t know how to implement it in this case.

const findOne = (list, { key, value }) => {  
    return new Promise ((resolve, reject) => {  
        const element = list.find(element => element[key] === value); 
        
        setTimeout(() => {  
            element 
            ? resolve(element.name) 
            :reject(new Error('ERROR: Element not found')); 
        }, 2000); 
    });
  }
  
  const users = [  
  {
    name: 'Carlos', 
    rol: 'Teacher' 
  },
  {
    name: 'Ana', 
    rol: 'Boss' 
  }
  ];


console.log('findOne User'); 

async function fetchData(){ 
  try { 
    const findUser = await findOne(users,{key: 'name', value: 'Carlos'}); 
    console.log("user:" + findUser); 
  }catch(err){ 
    console.log(err.message); 
  }
    
}

fetchData(); 

I have this code to search if a user is in the list or not. The thing is, I need to implement the calls to findOne in parallel. How can I add the promise.allSettled?

As is the code, how can I create multiple calls to findOne? I have reviewed the documentation of the Promises but I don’t know how to implement it in this case.

I don’t know how to try it anymore… thanks!

Answer

You would then want to pass a number of names to find to fetchData, and map those names to calls to findOne. Then call Promise.allSettled on the promises that you get back from that mapping. Finally deal with the returned settled-array as you wish:

const findOne = (list, { key, value }) => new Promise ((resolve, reject) => {  
    const element = list.find(element => element[key] === value); 
    setTimeout(() => element ? resolve(element.name) 
                             : reject(new Error('ERROR: Element not found'))
    , 2000); 
});
  
const users = [{name: 'Carlos', rol: 'Teacher'}, {name: 'Ana',  rol: 'Boss'}];

console.log('findOne User'); 

async function fetchData(names) {
  const promises = names.map(value => findOne(users, {key: 'name', value }));
  let results = await Promise.allSettled(promises);
  console.log(results);
}

fetchData(["Carlos", "Helen", "Ana"]);