已调用NodeJS异步回调

时间:2018-06-21 06:02:44

标签: node.js serial-port async.js

我一直在搜索,但是找不到在我的代码中导致此错误的原因:

  

(节点:7672)UnhandledPromiseRejectionWarning:错误:回调为   已经在C:\ Respaldos \ SerialReceive \ node_modules \ async \ dist \ async.js:966:32

处调用      

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

这是我的代码:

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();
    }
});

您能帮我发现错误吗?

致谢

1 个答案:

答案 0 :(得分:1)

我必须完全重写我的函数。如果有人遇到同样的问题,我会把它留在这里

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;
    }
}