admin管理员组文章数量:1291447
I wrote a module for my Node.js project which processes some data and is supposed to return the result, like that:
var result = require('analyze').analyzeIt(data);
The problem is that analyze.js
depends on an asynchronous function. 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. But how can I solve that?
I wrote a module for my Node.js project which processes some data and is supposed to return the result, like that:
var result = require('analyze').analyzeIt(data);
The problem is that analyze.js
depends on an asynchronous function. 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. But how can I solve that?
1 Answer
Reset to default 10You 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. The first two are more Node-like, the promise stuff is very au currant.
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:
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.
本文标签: javascriptReturn value from Nodejs module with asynchronous functionStack Overflow
版权声明:本文标题:javascript - Return value from Node.js module with asynchronous function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741531731a2383793.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论