custom promise

by Artem

JavaScript

'use strict';

class MyPromise {
	constructor(fn) {
		this.chain = [];
		fn(resolvedValue => {
			this.value = resolvedValue;
			this.callResolvers();
		});
	}
	
	then(resolve) {
		this.chain.push(resolve);
		this.callResolvers();
	}
	
	callResolvers() {
		this.chain.forEach(f => {
			f(this.value);
		});
	}

}

const p = new MyPromise(resolve => {
	setTimeout(() => {
		resolve('Promise has been resolved after 1sec');
	}, 1000);
});


setTimeout(() => {
	p.then(value => {
		console.log(value);
	});
}, 2000);