我正在尝试通过 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/