I have a nested function that does some I/O and calls a callback once it has finished with the resulting data. Something like this:
function getStatus(returnCallback, errorCallback) {
sendRequest('someData', returnCallback, errorCallback)
}
whereby sendRequest() is a function that interacts with hardware and calls the returCallback with the data that it got from the hardware or the errorCallback in case something went wrong. My problem now is, that the data that the hardware returns is a really long string that consists of different numbers that represent different parameters. What I want to do is manipulate the data that is given to the returnCallback and create and object with a property for each parameter. Is there a way to do that? I already tried using async.waterfall
function getStatus(returnCallback, errorCallback) {
let returnArray = {};
async.waterfall([
function (callback) {
sendRequest('someData', callback, errorCallback);
},
function (data, callback) {
returnArray.statusBits = data.slice(0, 6);
returnArray.faultBits = data.slice(7, 13);
returnArray.alertBits = data.slice(14, 20);
returnArray.pumpRotationSpeed = parseInt(data.slice(21, 26));
returnArray.motorPower = parseInt(data.slice(27, 31));
returnArray.frequencyConverterTemperature = parseInt(data.slice(36, 39));
returnArray.pumpOperationTime = parseInt(data.slice(44, 48));
callback(null, returnArray)
}
], returnCallback(returnArray));
but that does nothing. As it looks the second function in the waterfall is never called. This might be because the callback from the first function is not structured as expected in the waterfall and it returns with callback(data) instead of callback(null, data)
In async.waterfall
callback, the first argument is error
, also, you are supposed to wait for the end of the waterfall before exiting the function. The correct code would be:
function getStatus(returnCallback, errorCallback) {
let returnArray = {};
async.waterfall([
function (callback) {
//First step
sendRequest('someData', function (data) {
//Everything is fine, continue
callback(null, data);
}, function (error) {
//Error, skip all remaining step, and handle the error
callback(error);
});
},
function (data, callback) {
//Second step
returnArray.statusBits = data.slice(0, 6);
returnArray.faultBits = data.slice(7, 13);
returnArray.alertBits = data.slice(14, 20);
returnArray.pumpRotationSpeed = parseInt(data.slice(21, 26));
returnArray.motorPower = parseInt(data.slice(27, 31));
returnArray.frequencyConverterTemperature = parseInt(data.slice(36, 39));
returnArray.pumpOperationTime = parseInt(data.slice(44, 48));
callback(null, returnArray)
}
//In normal case, error will be null, and the param will be the last passed to the callback of the last step
], function (error, returnArray) {
//If there is a error (like error in step 1)
if(error) {
//Handle the error
errorCallback(error);
} else {
//No error, continue with the normal callback
returnCallback(returnArray);
}
});
}