欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

面试中常考的源码实现|promsie相关方法(all、race、any、allsettled和finally)

程序员文章站 2022-06-09 12:49:15
...

Promise相关面试常撕代码

all

Promise.myAll = function (iterators) {
	const promises = Array.from(iterators);
	const num = promises.length;
	const resolvedList = new Array(num);
	let resolveNum = 0;
	return new Promise((resolve, reject) => {
		promises.forEach((promsie, index) => {
			Promise.resolve(promise)
			.then(value => {
				resolvedList[index] = value;
				if (++resolveNum === num) {
					resolve(resolvedList);
				}
			})
			.catch(reject);
		});
	});
};

race

Promise.myRace = function (iterators) {
	const promises = Array.from(iterators);
	return new Promise((resolve, reject) => {
		promises.forEach((promise, index) => {
			Promise.resolve(promise)
			.then(resolve)
			.catch(reject);
		});
	});
};

any

Promise.myAny = function (iterators) {
	const promises = Array.from(iterators);
	const num = promises.length;
	const rejectedList = new Array(num);
	let rejectedNum = 0;
	return new Promise((resolve, reject) => {
		promises.forEach((promise, index) => {
			Promise.resolve(promise)
			.then(value => resolve(value))
			.catch(error => {
				rejectedList[index] = error;
				if (++resolvedNum === num) {
					reject(rejectedList);
				}
			})
		})
	})
}

allSettled

const formatSettledResult = (success, value) =>
	success
	? {status: 'fulfilled', value}
	: {status: 'rejected', reason: value};

Promise.allSettled = function (iterators) {
	const promises = Array.from(iterators);
	const num = promises.length;
	const settledList = new Array(num);
	let settledNum = 0;
	return new Promise((resolve, reject) => {
		promises.forEach((promise, index) => {
			Promise.resolve(promise)
			.then(value => {
				settledList[index] = formatSettledResult(true, value);
				if (++settledNum === num) {
					resolve(settledList);
				}
			})
			.catch(error => {
				settledList[index] = formatSettledResult(false, error);
				if (++settledNum === num) {
					resolve(settledList);
				}
			})
		})
	})
}

finally

Promise.prototype.finally = function (fn) {
	return this.then(
		value => Promsie.resolve(fn()).then(() => value);
		error => Promise.resolve(fn()).then(() => {
			throw error;
		})
	)
}