[英]Return value from Node.js module with asynchronous function
I wrote a module for my Node.js project which processes some data and is supposed to return the result, like that: 我为我的Node.js项目编写了一个模块,它处理一些数据并且应该返回结果,如下所示:
var result = require('analyze').analyzeIt(data);
The problem is that analyze.js
depends on an asynchronous function. 问题是
analyze.js
依赖于异步函数。 Basically it looks like this: 基本上它看起来像这样:
var analyzeIt = function(data) {
someEvent.once('fired', function() {
// lots of code ...
});
return result;
};
exports.analyzeIt = analyzeIt;
Of course, this cannot work because result
is still empty when it is returned. 当然,这不起作用,因为返回时
result
仍然是空的。 But how can I solve that? 但是我该怎么解决呢?
You solve it the same way Node solves it in its API: With a callback, which might be a simple callback, an event callback, or a callback associated with a promise library of some kind. 你可以用它在API中解决它的方式来解决它:使用回调,它可能是一个简单的回调,一个事件回调或一个与某种类型的promise库相关的回调。 The first two are more Node-like, the promise stuff is very au currant.
前两个更像Node,承诺的东西非常好吃。
Here's the simple callback way: 这是简单的回调方式:
var analyzeIt = function(data, callback) {
someEvent.once('fired', function() {
// lots of code ...
// Done, send result (or of course send an error instead)
callback(null, result); // By Node API convention (I believe),
// the first arg is an error if any,
// the second data if no error
});
};
exports.analyzeIt = analyzeIt;
Usage: 用法:
require('analyze').analyzeIt(data, function(err, result) {
// ...use err and/or result here
});
But as Kirill points out , you might want to have analyzeIt
return an EventEmitter
and then emit a data
event (or whatever event you like, really), or error
on error: 但是正如Kirill指出的那样 ,你可能想要
analyzeIt
返回一个EventEmitter
,然后发出一个data
事件(或者你喜欢的任何事件),或者error
时出错:
var analyzeIt = function(data) {
var emitter = new EventEmitter();
// I assume something asynchronous happens here, so
someEvent.once('fired', function() {
// lots of code ...
// Emit the data event (or error, of course)
emitter.emit('data', result);
});
return emitter;
};
Usage: 用法:
require('analyze').analyzeIt(data)
.on('error', function(err) {
// ...use err here...
})
.on('data', function(result) {
// ...use result here...
});
Or, again, some kind of promises library. 或者,再一次,某种承诺库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.