实现Promise.allSettled

业务场景

微信小程序中多张图片选择后一起上传时需判断多张图片的异步上传结果,成功了几张,失败了几张
最新ES2020已有Promise.allSettled,可在代码中先查看是否已有

代码

    Promise.allSettled = Promise.allSettled || function(promises) {
        return new Promise(function(resolve, reject) {
            if (!Array.isArray(promises)) {
                return reject(
                    new TypeError("arguments must be an array")
                );
            }
            var resolvedCounter = 0;
            var promiseNum = promises.length;
            var resolvedValues = new Array(promiseNum);
            for (var i = 0; i < promiseNum; i++) {
                (function(i) {
                    Promise.resolve(promises[i]).then(
                        function(value) {
                            resolvedCounter++;
                            resolvedValues[i] = value;
                            if (resolvedCounter == promiseNum) {
                                return resolve(resolvedValues);
                            }
                        },
                        function(reason) {
                            resolvedCounter++;
                            resolvedValues[i] = reason;
                            if (resolvedCounter == promiseNum) {
                                return reject(reason);
                            }
                        }
                    );
                })(i);
            }
        });
    };

你可能感兴趣的:(实现Promise.allSettled)