[英]How to return value from a function in a exported (imported through “require”) module in node.js?
I have a common module that will be used by several apps. 我有一个通用模块,将由多个应用程序使用。 The module has a object that has several methods.
该模块的对象具有几种方法。 I import the object through the require statement but I am having problem in understanding how I can get the returned value in an asynchronous programming model.
我通过require语句导入对象,但是在理解如何在异步编程模型中获取返回值时遇到问题。 Let me clarify it here in the following over-simplified pseudo-code:
让我在下面的过度简化的伪代码中进行澄清:
File common_module.js: 文件common_module.js:
var mysql = require('mysql');
exports.f1 = function() {
var connection_pool = mysql.createPool({host: 'xxx', user:..});
connection_pool.getConnection(function(err, connection) {
connection.query('SELECT c1 from t1 where c2 = ?', value, function(err, rows) {
value_to_return = rows[0].content; //string type
});
});
return (value_to_return);
}
The main app is, lets say, main.js: 可以说,主要应用程序是main.js:
db_getval = require('./common_module.js');
console.log(db_getval.f1());
It will always complain that value_to_return is undefined because the return statement is executed without waiting for the query to complete (thanks to asynchronous programming model). 总是会抱怨value_to_return是未定义的,因为执行return语句时无需等待查询完成(由于异步编程模型)。 Though this is a mysql query related problem here, it will be true for many other scenarios too.
尽管这是与mysql查询相关的问题,但对于许多其他情况也是如此。 How do I get around this?
我该如何解决? I am missing something basic here...
我在这里缺少一些基本的东西...
In this case, you can either use promises, or callbacks. 在这种情况下,您可以使用Promise或回调。
Callbacks in node are sort of the de-facto way of handling this kind of work: 节点中的回调实际上是处理此类工作的一种方式:
var mysql = require('mysql');
exports.f1 = function (cb) {
var connection_pool = mysql.createPool({
host: 'xxx',
user: ..
});
connection_pool.getConnection(function (err, connection) {
if (err) {
return cb(err);
}
connection.query('SELECT c1 from t1 where c2 = ?', value, function (err, rows) {
if (err) {
return cb(err);
}
cb(null, rows[0].content);
});
});
};
// usage...
theModule(function (err, result) {
console.log(err, result);
});
That said, with the introduction of promises in node 0.12, promises are becoming far more popular due to more robust error handling. 也就是说,随着在节点0.12中引入Promise,由于更强大的错误处理,Promise变得越来越流行。 (Chaining is also very useful)
(连锁也非常有用)
var mysql = require('mysql');
exports.f1 = function (cb) {
return new Promise(function (resolve) {
var connection_pool = mysql.createPool({
host: 'xxx',
user: ..
});
connection_pool.getConnection(function (err, connection) {
if (err) {
throw err;
}
connection.query('SELECT c1 from t1 where c2 = ?', value, function (err, rows) {
if (err) {
throw err;
}
resolve(rows[0].content);
});
});
});
};
// usage...
theModule().then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err, err.stack);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.