forEach、map、reduce和promise那點事(下)


解決方案

老實說,forEach、map、reduce、filter 這些方法本意都是針對同步函數的,不太適合異步的場景。在異步的場景,建議使用 for 和 for of 方法

但是雖然他們都是針對同步函數的,還是有一些 hack 方法可以讓它們對異步函數也生效,比如 reduce 的 hack 代碼如下所示:

(async function () {
    const fetch = (forceTrue) => new Promise((resolve, reject) => {
        if (Math.random() > 0.2 || forceTrue) {
            resolve('success');
        } else {
            reject('error');
        }
    });

    const reduceResult = await [0,1,2].reduce(async (accu) => {
        const value = await fetch(true);
        const resolvedAccu = await accu;
        resolvedAccu.push(value);
        return resolvedAccu;
    }, []);

    console.log('====', reduceResult);
})()

上面的代碼有這些需要注意的地方:

  1. 由於累計器 accu 是 async 回調函數的返回值 promise,所以我們使用 await 讓它得出結果
  2. 由於最后的結果也是 promise,所以我們在前面加上了 await,但是await 只能在 async 函數里面使用,所以我們在匿名函數那里加上了 async。

promise

上面讓我想起了 promise 的一種使用場景:我們知道 promise.all 可以獲得同步的 promise 結果,但是它有一個缺點,就是只要一個 reject 就直接返回了,不會等待其它 promise 了。那么怎么實現多個 promise 同步執行,不管有沒有拋出錯誤,都把結果收集起來

一般來說可以使用 for 循環解決,示例如下:

Promise.myAll = function (promiseArr) {
    const len = promiseArr.length;
    const result = [];
    let count = 0;

    return new Promise((resolve, reject) => {
        for (let i = 0; i < len; ++i) {
            promiseArr[i].then((res) => {
                result[i] = res;
                ++count;

                if (count >= len) {
                    resolve(result);
                }
            }, (err) => {
                result[i] = err;
                ++count;

                if (count >= len) {
                    resolve(result);
                }
            });
        }
    });
}

// test
const fetch = (forceTrue) => new Promise((resolve, reject) => {
    if (Math.random() > 0.2 || forceTrue) {
        resolve('success');
    } else {
        reject('error');
    }
});

Promise.myAll([fetch(), fetch(), fetch()])
    .then(res => console.log(res));  // ["success", "success", "error"]

但是如果注意到 promise 的then 方法和 catch 方法都會返回一個 promise的話,就可以用下面的簡單方法:

Promise.myAll = function (promiseArr) {
    // 就這一行代碼!
    return Promise.all(promiseArr.map(item => item.catch(err => err)));
}

// test
const fetch = (forceTrue) => new Promise((resolve, reject) => {
    if (Math.random() > 0.2 || forceTrue) {
        resolve('success');
    } else {
        reject('error');
    }
});

Promise.myAll([fetch(), fetch(), fetch()])
    .then(res => console.log(res)); // ["error", "error", "success"]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM