How to resolve a promise with a certain condition?

I'm new to JavaScript and I am really confused about the documentation for promises. I have the following case, when I have a bunch of users, and for each user I execute the async function, in which I do some calculations for this user and add the result with the user to the array. From what I understood from the documentation, I need to get a promise every time the asynchronization function is executed, and add all the promises to the list of promises that allow when the resulting array is passed to it as follows:

 someFunction = () => {
   var promises = [];
   users.forEach(user => {
       var promise = asyncFunction(user).callback(callBackValue => {
         // Run some checks and add the user to an array with the result
         if (checksAreGood) {
           usersArray.push({user: user, result: callBackValue});
         }
       });
       promises.push(promise);
   });
   return Promise.all(promises).then(() => Promise.resolve(matches));
 };

: , , , , 20, , , 20, . , , 20 . , , . , 1000 , , async , 20.

+4
1

, 20 , :

 async function someFunction(){
  const results = [];
  for(const user of users){
     const result = await asyncFunction(user);
     // Run some checks and add the user to an array with the result
     if(!someChecksGood) continue;
     results.push(result);
     if(results.length >= 20) break;
  }
  return results;
 }

"", , . , , , :

 async function someFunction(){
  const results = [];
  async function process(user){
    const result = await asyncFunction(user);
    if(!someChecksGood || results.length >= 20) return;
    results.push(result);
   }
   await Promise.all(users.map(process));
   return results;
 }

, . , , "" , , dbs , , , , "" , , :

  async function someFunction(){
    //Chunk the users
    const chunks = [], size = 5;
    for(var i = 0; i < users.length; i += size)
      chunks.push( users.slice(i, i + size));
    //the method to create the results:
    const results = [];
    async function process(user){
      const result = await asyncFunction(user);
      if(!someChecksGood || results.length >= 20) return;
      results.push(result);
    }
    //iterate over the chunks:
    for(const chunk of chunks){
      await Promise.all(chunk.map(process));
      if(results.length >= 20) break;
    }
    return results;
 }
+4

Source: https://habr.com/ru/post/1691320/


All Articles