Return 来自具有异步功能的 Node.js 模块的值
Return value from Node.js module with asynchronous function
我为我的 Node.js 项目编写了一个模块,它处理一些数据并且应该 return 结果,就像这样:
var result = require('analyze').analyzeIt(data);
问题是 analyze.js
依赖于一个异步函数。基本上它看起来像这样:
var analyzeIt = function(data) {
someEvent.once('fired', function() {
// lots of code ...
});
return result;
};
exports.analyzeIt = analyzeIt;
当然,这行不通,因为 result
在 returned 时仍然是空的。但是我该如何解决呢?
您解决它的方式与 Node 在其 API 中解决它的方式相同:使用回调,它可以是简单的回调、事件回调或与某种承诺库关联的回调。前两个更像 Node,promise 的东西非常 au currant。
这里是简单的回调方式:
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;
用法:
require('analyze').analyzeIt(data, function(err, result) {
// ...use err and/or result here
});
但是作为 , you might want to have analyzeIt
return an 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;
};
用法:
require('analyze').analyzeIt(data)
.on('error', function(err) {
// ...use err here...
})
.on('data', function(result) {
// ...use result here...
});
或者,同样,某种 promises 库。
我为我的 Node.js 项目编写了一个模块,它处理一些数据并且应该 return 结果,就像这样:
var result = require('analyze').analyzeIt(data);
问题是 analyze.js
依赖于一个异步函数。基本上它看起来像这样:
var analyzeIt = function(data) {
someEvent.once('fired', function() {
// lots of code ...
});
return result;
};
exports.analyzeIt = analyzeIt;
当然,这行不通,因为 result
在 returned 时仍然是空的。但是我该如何解决呢?
您解决它的方式与 Node 在其 API 中解决它的方式相同:使用回调,它可以是简单的回调、事件回调或与某种承诺库关联的回调。前两个更像 Node,promise 的东西非常 au currant。
这里是简单的回调方式:
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;
用法:
require('analyze').analyzeIt(data, function(err, result) {
// ...use err and/or result here
});
但是作为 analyzeIt
return an 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;
};
用法:
require('analyze').analyzeIt(data)
.on('error', function(err) {
// ...use err here...
})
.on('data', function(result) {
// ...use result here...
});
或者,同样,某种 promises 库。