Problem description

  • Before handwritingPromiseIn, we have finishedresolve,reject,then,allMethod. Now let’s go ahead and finishraceMethods.

solution

  • First of all,raceMethod, as well as the name, the competition, that is to see the first 🥇, so,raceThe processing logic is, whoever completes the first execution, prints that one. Nothing else.
  • Now let’s do a preliminary implementationraceThis method.

The preliminary implementation

  • Define a class method race that passes an array type. If it is not an array type, an error message is required.
  • It then iterates through the objects in the array, then executes them, and terminates if there is an output.
race(promises) {
   return new Promise((resolve,reject) = >{
   // pit 1: We need to make a type judgment on the parameters passed in
       if(!Array.isArray(promises)){
          return reject(new Error('Parameter must be an array type! '))}Promise.forEach(promise= >{
       // Pit 2: Use Promise. Resolve to prevent the current traversal object from being of a non-Promise type
           Promise.resolve(promise).then(data= >{
               resolve(data)
           }, err= >{
               reject(err)
           })
       })
   })
}

Copy the code

conclusion

  • Actually,raceThe implementation is relatively simple, that is, after the first object processing is completed, it is good to end the processing, but there are two points that need to pay attention to: 1. Check the type of the passed parameter to see if it is an array typeresolveMethod handles the object being traversed, otherwise, if not passedpromiseType in thethenAn error is reported during execution.

Front end small white, there are mistakes and improper place, forget you big god pointed out, if feel small brother code word is not easy, trouble to 👍, thank you!