Skip to content

Instantly share code, notes, and snippets.

class PromiseCopy{
finally( callback ){
// resolveOrReject : forward current #state.
// value : forward current #result.
/** curried function to pass Promise.resolve or
Promise.reject forward based on current Promise #state. **/
const commonCallback = ( resolveOrReject ) => ( value ) => {
const response = callback?.() ;
class PromiseCopy{
#handlers = [] ;
#queued = false ;
#dispatchCallbacks(){
if( this.#state === states.pending )return ;
if( this.#queued )return ;
const method = this.#state === states.fulfilled ? 'success' : 'fail' ; //handler method to call
class PromiseCopy{
catch( failurecallback ){
return this.then( undefined, failurecallback ) ;
}
}
class PromiseCopy{
then( successcallback , failurecallback ){
return new PromiseCopy( ( resolve, reject ) => {
/**
1. handlers is an Array which will store success handlers and error handlers.
2. Each entry will have :
- success method called with resolved value.
- failure method called with rejected value.
*/
class PromiseCopy{
static reject( reason ){
// We return a new Promise and pass the reason to reject method if Promise.reject is called directly.
if( !( this instanceof PromiseCopy ) ) return new PromiseCopy( ( _ , rej ) => rej( reason ) ) ;
//return if promise is settled.
if( this.#state !== states.pending )return ;
this.#state = states.rejected ;
class PromiseCopy{
static resolve( value ){
/*
1. We return a new Promise and pass the value to resolve method if Promise.resolve is called directly.
2. The resolve method of executor runs this same code with this instance added.
*/
if( !( this instanceof PromiseCopy ) ) return new PromiseCopy( res => res( value ) ) ;
//return if promise is settled.
const states = {
pending: 'PENDING',
fulfilled: 'FULFILLED',
rejected: 'REJECTED'
}
class PromiseCopy{
#state = states.pending // initial state of promise
#result = undefined ;
constructor( executor ){
Promise.resolve( 'create a resolved promise' );
//Promise {<fulfilled>: 'create a resolved promise'}
Promise.reject( 'create a rejected promise' );
//Promise {<rejected>: 'create a rejected promise'}
const error = null ;
//const error = 'error' ; // change to a truthy value to reject promise.
const promise = new Promise( ( resolve, reject ) => {
//asynchronous operation
setTimeout( () => {
return error ? reject( error ) : resolve( 'final data' ) ;
}, 3000 );
} );
// before 3 seconds:
const Matrix=(id)=>{
const STATE={
human_id:id,
current:'IDLING',
loaders:[]
}
const drive=()=>{
STATE.loaders.push('driving');