Js. myPromiseAll

Promise.all is all or nothing, it returns promise if all incoming promises resolved

const myPromiseAll = (promises) => {
    return new Promise((resolve, reject) => {
        let results = [];
        let countHandled = 0;
        for (let i = 0; i < promises.length; i++) {
            promises[i].then((result) => {
                results[i] = result;
                countHandled++;
                (countHandled === promises.length) && resolve(results);
            }).catch((err) => {reject(err)});
        }
    })
}

chain version, not correct

const handlePromise = (promise, results) => {
    return promise.then((r) => results.push(r));
}

const myPromiseAll = (promises) => {
    let results = [];
    let chain = Promise.resolve();
    for (let i = 0; i < promises.length; i++) {
        chain = chain.then(() => handlePromise(promises[i], results));
    }

    return new Promise((resolve, reject) => {
            chain.then(() => resolve(results)).catch((e) => reject(e));
        }
    )
}

version below doesn’t work properly

const myPromiseAll = (promises) => {
    return new Promise((resolve, reject) => {
        let results = [];
        for (let i = 0; i < promises.length; i++) {
            Promise.resolve(promises[i]).then((result) => {
                results.push(result); 
                (i === promises.length - 1) && resolve(results);
            }).catch((err) => {reject(err)});
        }
    })
}

lets test

let p1 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise1"));
let p2 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise2"));
let p3 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise3"));

lets reject some incoming promise

let p1 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise1"));
let p2 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise2"));
let p3 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "promise3"));
let p4 = new Promise((resolve, reject) => reject('rejected'));
Promise.all([p1, p2, p3, p4]).then(value => console.log('Promise.all', value), reason => console.log('Promise.all', reason));
myPromiseAll([p1, p2, p3, p4]).then(value => console.log('myPromiseAll', value), reason => console.log('myPromiseAll', reason));
This entry was posted in Без рубрики. Bookmark the permalink.