Fork me on GitHub

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"]
posted @ 2020-11-03 08:19  馒头加梨子  阅读(695)  评论(0编辑  收藏  举报