手写Promise.all和Promise.race

Posted 煜成'Studio

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写Promise.all和Promise.race相关的知识,希望对你有一定的参考价值。

手写Promise.all和Promise.race

Promise.all

function promiseAll (promises) {
	if (!Array.isArray(promises)) {
		throw new Error ("promises must to be an array!!!");
	}
	return new Promise (function (resolve, reject) {
		let promiseNum = promises.length;
		let resolvedCount = 0;
		let resolveValues = new Array(promiseNum);
		try {
			for (let i = 0; i < promiseNum; i++) {
                promises[i].then(function (value) {
                    resolveValues[i] = value;
                    if (++resolvedCount === promiseNum) {
                        resolve(resolveValues);
                    }
                })
		} catch (error) {
			reject(error);
		}
	})
}

Promise.race

function promiseRace(promise) {
	if (!Array.isArray (promises)) {
		throw new Error ("promises must be an array!!!");
	
	}
	let resolved = false;
	return new Promise(function (resolve, reject) {
		try{
			promises.forEach(p =>
                p.then(data => {
                	if (!resolved) {
                		resolved = true;
                		resolve (data);
                	}
                })
            )
		} catch (error) {
			reject(error);
		}
	})
}

以上是关于手写Promise.all和Promise.race的主要内容,如果未能解决你的问题,请参考以下文章

手写promise,promise.all,promise.race

因为实现不了Promise.all,一场面试凉凉了

Promise的特性

Promise.all和Promise.race区别,和使用场景

promise.all 怎么用

实现promise.all方法