Chico3001
Chico3001

Reputation: 1963

NodeJS Async Callback already called

I have been searching but i cannot find what causes this error on my code:

(node:7672) UnhandledPromiseRejectionWarning: Error: Callback was already called at C:\Respaldos\SerialReceive\node_modules\async\dist\async.js:966:32

at SerialPort. (C:\Respaldos\SerialReceive\receive.js:35:4)

This is my code:

function receiveEnq(callback) {
    port.on('data', function (data) {
        if ((data.length == 1) && (data[0] == 5)) {
            console.log('Received: ENQ');

            return callback(null, 'done');
        } else {
            callback('Error', 'Received:' + data);
        }
    });
}

function sendAck(err, callback) {
    port.write(Buffer.from([6]));
    console.log('Transmitted: ACK');

    callback(null, payload[sequence]);
}

function receiveData(data, callback) {
    port.on('data', function (data) {
        console.log(data);

        callback(null, 'done');
    });
}

async.waterfall([
    receiveEnq,
    sendAck,
    receiveData
], function (err, result) {
    console.log(result)

    if (err) {
        process.abort();
    }
});

Can you help me spot the error?

Regards

Upvotes: 0

Views: 674

Answers (1)

Chico3001
Chico3001

Reputation: 1963

I had to completely rewrite my function. I leave it here in case someone has the same problem

const SerialPort = require('serialport');
const ByteLength = SerialPort.parsers.ByteLength;
const port = new SerialPort("COM6");
const parser = new ByteLength({length: 1});
port.pipe(parser);

var state = 0;
var cache = [];
var history;

parser.on('data', function (data) {
    cache.push(data[0]);
    flowcontrol();
});

function porterr() {
    console.log('error');
    process.exit(1);
}

function flowcontrol() {

    switch (state) {

        case 0:
            // Recives 1 byte
            if (cache.length !== 1) {
                return;
            }

            // Sends Answer and changes to next state
            port.write(Buffer.from([6]));
            state++;
            cache.length = 0;
            break;

        case 1:
            // Recives 1 byte
            if (cache.length !== 1) {
                return;
            }

            // Sends Answer and changes to next state
            port.write(Buffer.from([6]));
            state++;
            cache.length = 0;
            break;

        // Define more states here... 
        // .....
        // .....
        // .....

        default:
            console.log('state not defined');
            break;
    }
}

Upvotes: 1

Related Questions