Handwritten JS implements promises in various ways.
Promise.resolve()
(Sometimes you need to turn an existing object into a Promise object, and the promise.resolve method also does this.) 1. Pass the parameter as a Promise and return it directly. 2. Pass the parameter as a Thenable object, and the returned Promise will follow the object and take its final state as its own state. 3. In other cases, return a Promise object with this value as the success state.
Promise. All ()
- Functional specifications
If one of the arguments fails, the Promise object returned by promise.all fails.
- Parameters that
(1) If the iterable passed in is empty, promise. all will return a Promise in a completed state synchronously. (2) The argument passed does not have to be an array object. It can be a “traverser”. (3) In any case, promise.all returns an array of Promise completion states.
- implementation
/ / all implementation
Promise.all = function (arr){
let n = 0; // Declare a calculator. Resolve if all execute successfully
let resolveValue = []; // An array of results
let len = arr.length;
// If the argument passed is an empty iterable, resolve is passed
if (len === 0){
resolve(resolveValue);
return;
}
return new Promise(function(resolve,reject){
for (let i=0; i<len; i++){// if successful, add the result to the array with n++
// Why not just promise[I]. Then, because promise[I] may not be a promise
Promise.resolve(arr[i]).then(res= >{
resolveValue.push(res);
n++;
Resolve () if n is the length of the array
if(n === len){
resolve(resolveValue);
}
})
.catch(err= >{ reject(err); })}})}Copy the code
Testing the all method
// Test the all method
let p1 = new Promise(function(resolve,reject){
let x =0;
setTimeout(function(){
x++;
if(x==1){ resolve(x); }},1000)});let p2 = new Promise(function(resolve,reject){
let x = 0;
setTimeout(function(){
x++;
if(x==1){ resolve(x); }},1000)})Promise.all([p1,p2]).then((res) = >{
console.log(res)
})
Copy the code
Promise.race
- Functional specifications
The promise.race (iterable) method returns a Promise that is resolved or rejected once a Promise in the iterator is resolved or rejected.
- Parameters that
It returns a Promise value.
- Code implementation
/ / race
Promise.race = function(arr){
return new Promise((resolve,reject) = >{
let len = arr.length;
for (let i=0; i<len; i++){Promise.resolve(arr[i]).then(res= >{
resolve(res);
}).catch(err= >{ reject(err); })}})}Copy the code
How do async and await simplify promises
Benefits: 1. Simplify use of Promise objects: Use then() to specify success/failure callbacks without synchronous encoding (there are no callbacks) to implement asynchronous flow.