Problem description
- Before handwriting
Promise
In, we have finishedresolve,reject,then,all
Method. Now let’s go ahead and finishrace
Methods.
solution
- First of all,
race
Method, as well as the name, the competition, that is to see the first 🥇, so,race
The processing logic is, whoever completes the first execution, prints that one. Nothing else. - Now let’s do a preliminary implementation
race
This 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,
race
The 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 typeresolve
Method handles the object being traversed, otherwise, if not passedpromise
Type in thethen
An error is reported during execution.