当前位置:网站首页>Realize all, race, allsettled and any of the simple version of promise by yourself

Realize all, race, allsettled and any of the simple version of promise by yourself

2022-07-07 12:29:00 Xiaoding Chong duck!

Supplementary knowledge :

  • promise There are three states :pending、rejected、fulfilled
  • Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state
  • Once the status changes , It won't change ,Promise Object state changes , There are only two possibilities : from pending Turn into fulfilled And from the pending Turn into rejected

One 、promise.all

characteristic :

  • Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following Promise.resolve Method , Convert parameter to Promise example , Further processing )
  • The return value is promise example
  • If it all works , The status changes to resolved, And the return value forms an array and is passed to the callback
  • Whenever there is a failure , The status changes to rejected, And will error Return to callback
  • The return result is strictly in accordance with the incoming promise Sequential return

Code :

function all(iterable) {
    return new Promise((resolve, reject) => {
        let result = []; //  Store results 
        let count = 0;   // There are several records resolve
        //  empty 
        if (!iterable || iterable.length === 0) {
            resolve([]);
            return;
        }

        for (let i = 0; i < iterable.length; i++) {
            let promise = iterable[i];
            //  If not promise example , It turns into promise
            if (!(promise instanceof Promise)) {
                promise = Promise.resolve(promise);
            }
            promise.then(
                (value) => {
                    result[i] = value;
                    count++;
                    if (count === iterable.length) {
                        resolve(result);
                    }
                }
            ).catch(
                (err) => {
                    reject(err);
                }
            );
        }
    });
}

verification :

//  There is one reject verification 
let p1 = Promise.resolve(1),
    p2 = Promise.reject(2),
    p3 = Promise.resolve(3);

all([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// 2 err
//  All of them resolve verification 
let p1 = Promise.resolve(1),
    p2 = Promise.resolve(2),
    p3 = Promise.resolve(3);

all([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// [ 1, 2, 3 ] res
//  There are not promise verification 
let p1 = Promise.resolve(1),
    p2 = Promise.resolve(2),
    p3 = Promise.resolve(3);

all([0,p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// [ 0, 1, 2, 3 ] res

Two 、promise.race

race It's a game 、 The meaning of competition , So as the name suggests , It's about who's fast , Just go back to who .

characteristic :

  • Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following Promise.resolve Method , Convert parameter to Promise example , Further processing )
  • The return value is promise example
  • There is an instance of changing state ( Whether it's resolve still reject), ends , And return the result of this instance to the callback function

Code :

function race(iterable) {
    return new Promise((resolve, reject) => {
        //  empty 
        if (!iterable || iterable.length === 0) {
            resolve([]);
            return;
        }

        for (let i = 0; i < iterable.length; i++) {
            let promise = iterable[i];
            //  If not promise example , It turns into promise
            if (!(promise instanceof Promise)) {
                promise = Promise.resolve(promise);
            }
            promise.then(
                (value) => {
                    resolve(value);
                }
            ).catch(
                (err) => {
                    reject(err);
                }
            );
        }
    });
}

verification :

//  All successfully verified 
let p1 = Promise.resolve(1),
    p2 = Promise.resolve(2),
    p3 = Promise.resolve(3);
    
race([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// 1 res
//  There are failed verifications 
let p1 = Promise.reject(1),
    p2 = Promise.reject(2),
    p3 = Promise.resolve(3);
    
race([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// 1 res

 

3、 ... and 、promise.allSettled

characteristic :

  • Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following Promise.resolve Method , Convert parameter to Promise example , Further processing )
  • The return value is promise example
  • It ends only when all results are returned ( Whether it's resolve still reject), Return all results as an array , Each result is an object , contain value and status,ES2020 introduce
[{ status: "rejected", reason: error1 }, { status: "fulfilled", value: 1 }];

Code :

//  Process the returned result in the specified format 
const formatSettledResult = (success, value) =>
  success
    ? { status: "fulfilled", value }
    : { status: "rejected", reason: value };

function allSettled(iterable) {
    return new Promise((resolve, reject) => {
        let len = iterable.length;
        //  empty 
        if (!iterable || len === 0) {
            resolve([]);
            return;
        }
        let result = []; //  Save the finished results  
        for (let i = 0; i < len; i++) {
            let promise = iterable[i];
            //  If not promise example , It turns into promise
            if (!(promise instanceof Promise)) {
                promise = Promise.resolve(promise);
            }
            promise.then(
                (value) => {
                    result[i] = formatSettledResult(true, value);
                    if (result.length === len) {
                        resolve(result);
                    }
                }
            ).catch(
                (err) => {
                    result[i] = formatSettledResult(false, err);
                    if (result.length === len) {
                        resolve(result);
                    }
                }
            );
        }
    });
}

  verification :

//  verification 
let p1 = Promise.reject(1),
    p2 = Promise.reject(2),
    p3 = Promise.resolve(3);
    
allSettled([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

/*[
  { status: 'rejected', reason: 1 },
  { status: 'rejected', reason: 2 },
  { status: 'fulfilled', value: 3 }
] res
*/

Four 、promise.any

And promise.all Just the opposite

characteristic :

  • Parameters are iteratable objects (Iterator), Every item inside is promise example ( If not , I'll call the following Promise.resolve Method , Convert parameter to Promise example , Further processing )
  • The return value is promise example
  • As long as one of the parameter instances becomes fulfilled state , The packaging instance will become fulfilled state ; If all parameter instances become rejected state , The packaging instance will become rejected state , And return the result as an array
  • Not because of one Promise become rejected State and end

Code :

function any(iterable) {
    return new Promise((resolve, reject) => {
        let len = iterable.length;
        //  empty 
        if (!iterable || len === 0) {
            resolve([]);
            return;
        }
        let result = []; //  preservation rejected Result  
        for (let i = 0; i < len; i++) {
            let promise = iterable[i];
            //  If not promise example , It turns into promise
            if (!(promise instanceof Promise)) {
                promise = Promise.resolve(promise);
            }
            promise.then(
                (value) => {
                    resolve(value);
                }
            ).catch(
                (err) => {
                    result[i] = err;
                    if (result.length === len) {
                        reject(result);
                    }
                }
            );
        }
    });
}

verification :

//  verification 
let p1 = Promise.reject(1),
    p2 = Promise.reject(2),
    p3 = Promise.reject(3);
    
any([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// [ 1, 2, 3 ] err
//  verification 
let p1 = Promise.reject(1),
    p2 = Promise.reject(2),
    p3 = Promise.resolve(3);
    
any([p1,p2,p3]).then((res) => {
    console.log(res, 'res');
}).catch((err) => {
    console.log(err, 'err')
});

// 3 res

summary : That's all , Is it not difficult at all !! Just know everyone API Characteristics , It can be easily realized , But this is only a simple version , Poor fault tolerance , For reference only .

原网站

版权声明
本文为[Xiaoding Chong duck!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130617454667.html