This is the 22nd day of my participation in the August More Text Challenge

This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation. It is important to have a clear concept and clear implementation idea. It is suggested to explain the concept clearly first => write use cases => write pseudocode => implement specific functions, and then optimize step by step.

30. Promise.race

Analysis of the

We mentioned a Promise API promise.all, now let’s implement promise.race ()

See what promise.race () can do

The promise.race (iterable) method returns a Promise that is resolved or rejected once a Promise in the iterator is resolved or rejected.

grammar

Promise.race(iterable);
Copy the code

Parameter – iterable an iterable, like Array, like promise.all

Return value – Whenever a Promise in a given iteration is resolved or rejected, a pending Promise takes the value of the first Promise as its value, thereby resolving or rejecting it asynchronously (once the stack is empty).

describe

  • The race function returns a Promise that will be completed in the same way as the first Promise passed. It may be a high degree of completion or rejection, depending on which of the two is the first.

  • If the passed iteration is empty, the returned promise will wait forever.

  • If the iteration contains one or more non-promise values and/or resolved/rejected promises, promise.race resolves to the first value found in the iteration.

Here’s an example:

const promise1 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 500.'one');
});

const promise2 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 100.'two');
});

const promise3 = new Promise((resolve, reject) = > {
  setTimeout(reject, 300.'three');
});

Promise.race([promise1, promise2, promise3]).then((value) = > {
  console.log(value);
});
// two
// Print two because promise2 executes as soon as possible

Promise.race([promise1, promise3]).then((value) = > {
  // not called
  console.log(value);
}).catch(reason= > {
  console.log(reason, 'is reject');
});
// three is reject
// The fastest is to reject promise3, so go catch
Copy the code

Before implementing this approach, take a look at this handwritten promise.all

Handwritten implementation

const myPromiseRace = (iterableArr) = > {
  // Return a Promise
  return new Promise((resolve, reject) = > {
    if (!Array.isArray(iterableArr)) {
      return reject(new Error('params is not an iterator Array'))}// Start iterating over each iteration element
    for (item of iterableArr) {
      Promise.resolve(item).then((res) = > {
        // The PROMISE array returns any promise state changes
        resolve(res)
      }).catch(e= > {
        reject(e)
      })
    }
  })
} 

// Use our test case as well

const promise1 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 500.'one');
});

const promise2 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 100.'two');
});

const promise3 = new Promise((resolve, reject) = > {
  setTimeout(reject, 300.'three');
});

myPromiseRace([promise1, promise2, promise3]).then((value) = > {
  console.log(value);
});
// two

myPromiseRace([promise1, promise3]).then((value) = > {
  console.log(value);
}).catch(reason= > {
  console.log(reason, 'is reject');
});
// three is reject
Copy the code

No problem, then we’ll use this promise.race to limit the number of asynchronous concurrency.

31. Promise.allSettled

Analysis of the

In this article we introduce Promise.AllSettled

In simple terms, the promise.allSettled () method returns a Promise after all the given promises have fulfilled or rejected, with an array of objects, each representing the corresponding Promise result.

As we explained in a previous article, when we execute a Promise with promise.all (), reject is executed whenever any of the promises fails, reject is the first error message thrown, The success callback in.then is called only if all promises are resolve

Let’s go straight to the implementation, much like promise.all

Handwritten implementation

Write the test case first and make four promises. The fourth promise fails.

// Create a factory function that takes the name and asynchronous time
const promiseFactory = (name, wait, isFail = false) = > {
  return new Promise((resolve, reject) = > {
    // Asynchronous task (simulated with setTimeout)
    setTimeout(() = > {
      if(! isFail) { resolve(I was `${name}And I need${wait}Ms, successful ')}else {
        reject(I was `${name}And I need${wait}Ms, execution failed)
      }
    }, wait)
  })
}

let pro1 = promiseFactory('First asynchronous task'.3000)
let pro2 = promiseFactory('Second asynchronous task'.1000)
let pro3 = promiseFactory('Third asynchronous task'.2000)
let pro4 = promiseFactory('Fourth asynchronous task'.1500.true)
Copy the code

Then implement

const myPromiseAllSettled = (iterableArr) = > {
  return new Promise((resolve, reject) = > {
    if (!Array.isArray(iterableArr)) {
      return reject(new Error('params is not an iterator Array'))}let res = [], count = 0
    for (let i = 0; i < iterableArr.length; i++) {
      Promise.resolve(iterableArr[i]).then(value= > {
        res[i] = {status: "fulfilled".value: value}
      }).catch(err= > {
        res[i] = {status: "rejected".reason: err}
      }).finally(() = > {
        // Count each time until all execution is complete and return the result
        count++
        if (count === iterableArr.length) {
          resolve(res)
        }
      })
    }
  })
}

myPromiseAllSettled([pro2, pro1, pro3, pro4]).then(res= > {
  console.log(res) 
}, err= > {
  console.log(err)
})

// The result will be printed after 3 seconds and will be returned regardless of success or failure
/ / /
// {status: "depressing ", value:" I am the second asynchronous task, I need 1000 ms, execute successfully "},
// {status: "depressing ", value:" I am the first asynchronous task, I need 3000 ms, which is fulfilled successfully "},
// {status: "depressing ", value:" I am the third asynchronous task, I need 2000 ms, execute successfully "},
// {status: "rejected", reason: "I need 1500 ms "}
// ]
Copy the code

And so it worked.

In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference

  • Developer.mozilla.org/zh-CN/docs/…