React

by Abdul Ahmad

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}

React

async function handleReq(req) {
  const readRes = await readData({ data: '' });
  const writeRes = await writeData(({ db } = {}) => {
  	// do something with db
    console.log('data', db);
  });
  console.log('res', res);
}

class DbOperationProcessor {
	static nextId = 0;

  id = 0;
  operation = '';
  promise = {};

  constructor({ operation, resolve, reject } = {}) {
    this.id = ++DbOperationProcessor.nextId;
    this.operation = operation;
    this.promise = { resolve, reject };
    console.log('created new db operation: ' + this.id);
  }

  process() {
  	console.log('started processing operation: ' + this.id);
    try {
    	setTimeout(() => {
        this.operation();
        console.log('finished processing op: ' + this.id);
        this.promise.resolve('process id: ' + this.id);
      }, getRandomInt(1000, 3000));
    } catch (e) {
      this.promise.reject(e);
    }
  }
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


const STATUS__IDLE = 'idle';
const STATUS__PERFORMING_OP = 'performing_op';
const _database = {
    operationStatus: STATUS__IDLE,
    currentOperationBeingProcessed: {},
    data: {},
};

let operationQueue = [];

function readData({ } = {}) {

}

async function writeData({ callback } = {}) {
	console.log('* writing data *');
	let _resolve;
  let _reject;
  const promise = new Promise((resolve, reject) => {
  	_resolve = resolve;
    _reject = reject;
  });
  
  const operationProcessor = new DbOperationProcessor({
    resolve: _resolve,
    reject: _reject,
    operation: () => callback({ db: _database.data }),
  });
  console.log('added operation to queue: ' + operationProcessor.id);
  addOp({ operation: operationProcessor });
  
  const res = await promise;
  handleOpProcessingComplete();
  return res;
}

function addOp({ operation } = {}) {
	operationQueue.push(operation);
  // - attempt to process next operation when we add a...