Promise

by evgkch

JavaScript

// Constructor
function Promise(resolve,reject){
  this.result = void null;
  this.status = 'pending';
  // Resolve result and run queue of callbacks
  resolve(result=>{
    this.result = result;
    this.status = 'resolved';
    if (typeof(this._handler) == 'function')
      this._handler();
  });
}	

// Public methods
Promise.prototype.then = function(callback){
	return new Promise(resolve=>{
		if (this.status == 'pending')
    {
    	this._handler = ()=>{
    		resolve(callback(this.result));     
    	};
    }
		if (this.status == 'resolved')
    	resolve(callback(this.result));   	
  });
}

Promise.all = function(promisesList){
	return new Promise(resolve=>{
  	const buffer = [];
    const promisesListLength = promisesList.length;
    let counter = 0;
    function pushToBuffer(result, i){
    	buffer[i] = result;
      counter += 1;
      if (promisesListLength == counter)
      	resolve(buffer);
    }
    promisesList.forEach((promise, i)=>{
  		 promise.then(result=>pushToBuffer(result, i))
  	});
  }) 
}

const myPromise = () => new Promise(resolve=>{
	setTimeout(()=>{
  	resolve(2);
  },1000)
});

const a = myPromise().then(v=>{ console.log(v); return v ** 2; });
console.log(a);
const b = a.then(v=>{ console.log(v); return v ** 2; });
console.log(b);

console.log(Promise.all([myPromise(), myPromise()]))