在节点模块中使用异步 - 如何返回结果?

时间:2017-01-05 21:54:58

标签: javascript node.js asynchronous npm async.js

我正在为我的公司编写一个内部NPM模块,以便应用程序可以与我们拥有的硬件设备进行交互,我们已经有一个用于与之通信的库。问题是,我尝试编写的一种方法需要异步执行。我希望函数发送一个命令从设备读取,等待它返回(设备库处理这个),然后我解析结果。我希望其他开发人员能够调用exports.getResolution()来获取值。以下是我的文件片段以及相关部分:

var async = require('async');

exports.getResolution = async.series([
    function(callback) {
    board.sendAndReceive(bufferlib.generateBuffer("read", "0x00001220", "0x00000004"), (function(received) {
            var hex = bufferlib.sortReceivedHex(received);
            var status = parseInt('0x' + hex.substring(0, 1), 16);
            var verticalResolution = parseInt('0x' + hex.substring(1, 4), 16);
            var horizontalResolution = parseInt('0x' + hex.substring(5, 9), 16);
            callback(null, {
                'status': status,
                'vertical': verticalResolution,
                'horizontal': horizontalResolution
            });
        }));
    }
],
// optional callback
function(err, results) {
    status = results[0];
    return results[0];
});

console.log(exports.getResolution);

我曾尝试过回调地狱,Promises,蓝鸟,ES6异步功能以及其他一些解决方案,但我无法解决这个问题。我最近的尝试使用异步节点模块尝试异步执行代码,这是有效的,但现在我只需要获取exports.getResolution来返回最终回调接收的实际值。我究竟做错了什么?我能做些什么来完成这项工作?谢谢。

2 个答案:

答案 0 :(得分:1)

尝试使异步调用同步不是一个好主意。您需要做的是注册一个在结果存在时执行的方法。通常这些方法称为回调,但Promise是一种更好的方法来完成等待异步结果。

exports.getResolution = function() {
    return new Promise(function(resolve, reject) {
        function receiveHandler(received) {
            var hex = bufferlib.sortReceivedHex(received);
            var status = parseInt('0x' + hex.substring(0, 1), 16);
            var verticalResolution = parseInt('0x' + hex.substring(1, 4), 16);
            var horizontalResolution = parseInt('0x' + hex.substring(5, 9), 16);

            // If status would say something about it's success you could also
            // use reject instead of resolve to indicate failure
            resolve({
                'status': status,
                'vertical': verticalResolution,
                'horizontal': horizontalResolution
            });
        }

        board.sendAndReceive(bufferlib.generateBuffer("read", "0x00001220", "0x00000004"), receiveHandler);
    }
}

// Usage
exports.getResolution().then(function(response) {
  console.log('succesfully received response:', response);
}, function(response) {
  console.log('something went wrong:', response)
});

答案 1 :(得分:0)

执行此操作的正确方法是为getResolution函数提供回调参数。这就是它应该如何做到的。

exports.getResolution = function(callback) {
    board.sendAndReceive(bufferlib.generateBuffer("read", "0x00001220", "0x00000004"), function(received) {
        var hex = bufferlib.sortReceivedHex(received);
        var status = parseInt('0x' + hex.substring(0, 1), 16);
        var verticalResolution = parseInt('0x' + hex.substring(1, 4), 16);
        var horizontalResolution = parseInt('0x' + hex.substring(5, 9), 16);
        callback(null, {
            'status': status,
            'vertical': verticalResolution,
            'horizontal': horizontalResolution
        });
    });
}


console.log(exports.getResolution(function (err, results) {
    console.log(results);
}));

以上方式是正确的在JS中做事的方式。但是,如果您绝对需要使getResolution看起来是同步的,那么您可能需要查看this answer。但似乎您需要修改一些board函数以允许轮询...