Christoph Pohl Christoph Pohl - 3 months ago 9
Javascript Question

Manipulating data in a callback function

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)

Answer

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) {
            sendRequest('someData', function (data) {
                callback(null, data);
            }, 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)
        }
    ], function (error, returnArray) {
        if(error) {
            errorCallback(error);
        } else {
            returnCallback(returnArray));
        }
    });
}
Comments