javascript - 高速公路JS : Remote call to asyncronous function

标签 javascript node.js autobahn crossbar wamp-protocol

我正在尝试通过 WAMP 调用远程函数。但如果被调用的函数具有异步行为,我不知道如何编写它。在每个示例中,我都看到远程函数返回结果。如何以异步方式完成此操作(我通常使用回调)?

示例: 这是一个函数的注册,该函数将异步获取文件的内容。

session.register('com.example.getFileContents', getFileContents).then(
    function (reg) {
        console.log("procedure getFileContents() registered");
    },
    function (err) {
        console.log("failed to register procedure: " + err);
    }
);

这是我远程调用该函数的方法。

session.call('com.example.getFileContents', ["someFile.txt"]).then(
    function (res) {
        console.log("File Contents:", res);
    },
    function (err) {
        console.log("Error getting file contents:", err);
    }
);

但这是注册的实际函数。

function getFileContents(file) {
    fs.readFile(file, 'utf8', function(err, data) {

        // How do I return the data?
    });
}

如何从 getFileContents 返回数据,以便可以通过 WAMP 连接发回数据?我知道我可以使用 readFileSync 并返回它返回的内容。但我特别询问如何以异步方式执行此操作。

最佳答案

我想出了如何用 promise 来做到这一点。以下是如何使用 Promise 实现该函数。

var fs = require('fs');
var when = require('when');

function getFileContents(file) {
    var d = when.defer();
    fs.readFile(file, 'utf8', function(err, data) {
        d.resolve(data);
    });
    return d.promise;
}

关于javascript - 高速公路JS : Remote call to asyncronous function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437537/

相关文章:

node.js - Visual Studio Code 无法识别 ES6 语法

node.js - 如何使用 Bluebird Promise 修复 "Undefined response in pagination"(@google-cloud)

python-3.x - service_identity 已安装但无法正常工作

javascript - AngularJS 和 Autobahn.js WAMP 实现

javascript - 过滤函数中的对象字面量

javascript - 无法通过 JavaScript 将参数从 View 传递到 Controller

javascript - 使用 len 和 setter 续写密码验证失败

python - 高速公路,离开 onMessage block

javascript - JS 防止焦点上闪烁的输入边框

javascript - Node.js - 典型的回调问题