Skip to content

Instantly share code, notes, and snippets.

@fodra
Created August 24, 2017 03:50
Show Gist options
  • Save fodra/bda607317c020b16aa2c07c2650a24bb to your computer and use it in GitHub Desktop.
Save fodra/bda607317c020b16aa2c07c2650a24bb to your computer and use it in GitHub Desktop.
These are two examples on how to chain promises that need to be executed one after the other.
const readSession = function(portHandle, sectors) {
// this holds the result
let result = [];
// this is the entry point of the recursive func
let _readAll = function(sectorsToRead) {
// when there's no more sectore to read
// we stop and return the result
if (sectorsToRead.length === 0) {
return result;
}
// read the data from serial on the current sector
return Device.readChunk(portHandle, sectorsToRead.shift()).then((dataFromSerial) => {
// once we get the data, save it
result.push(dataFromSerial);
// call to read the next sector
return _readAll(sectorsToRead);
});
}
// main call to the start recursive function
return _readAll(sectors);
}
const readSession1 = function(portHandle, sectors) {
// setup the buffer that will contain all the sector data
let fullBuffer = new Buffer(PAYLOAD_LEN * sectors.length);
// this will iterate through the sector array starting from the first element
return sectors.reduce(function(previous, currentSector, index) {
// previous is a promise
// initial value is a promise with an empty buffer
return previous.then(function(previousValue) {
// we read the sector data here from serial
return Device.readChunk(portHandle, currentSector).then((dataFromSerial) => {
// copy the data to the buffer that will contain all the data
dataFromSerial.copy(previousValue, PAYLOAD_LEN*index);
// important! return the modified buffer, will be used in the next iteration
return previousValue;
});
})
// we shall start with an empty buffer
}, Promise.resolve(fullBuffer));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment