Promises

by lovinglobo

JavaScript

function getCdRomSector(driveNr, sectorNr) {
	// do something semi-intelligble here
  //...
  //...
  const cdRom = 
  	[
    	["0101010101", "1101010110", "11111111111"], // drive 0
      ["2222211451", "1101124121240", "11523235111"] // drive 1
    ];
   
  return new Promise(resolveFn  => {
  	setTimeout(() => {
  		const sectorData = cdRom[driveNr][sectorNr];
      return resolveFn(sectorData);
	  }, 1000);
	});
}

// sequential code without staircase!!!
getCdRomSector(1, 1).then(sectorData => {
  console.log("seq1", sectorData);
  return getCdRomSector(0, 0);
}).then(sectorData2 => {
  console.log("seq2", sectorData2);
});

// parallel 

Promise.all([
  getCdRomSector(1, 1), 
  getCdRomSector(0, 0)
]).then(results => {
  console.log("parallel", results);
  return getCdRomSector(1, 2);
}).then(moreSectoData => {
  console.log("sequential after parallel 2", moreSectoData);
});

///

(async function() {
	// sequential code 
	const x = await getCdRomSector(0, 0);
  const y = await getCdRomSector(0, 0);
	console.log("sequential", x, y);	
})();

(async function() {
	// parallel code 
  const a = getCdRomSector(0, 0);
  const b = getCdRomSector(1, 1)
	const results = [await a, await b];
	console.log("parallel", results);	
})();