我正在尝试像这样在node.js中导出变量:
let news = [];
const fetchNews = new Promise ((resolve, reject) => {
let query = 'SELECT id, name FROM news';
mysql.query(query, [], (error, results) => {
if (error)
reject({error: `DB Error: ${error.code} (${error.sqlState})`})
results = JSON.parse(JSON.stringify(results));
news = results;
resolve(results);
});
});
if(!news.length)
fetchNews
.then(results => {news = results})
.catch(err => {console.log('Unable to fetch news', err)});
exports.news = news;
当我在其他类似模块中使用此代码时:
const news = require('./news.js').news;
console.log(news);
//returns [];
有人可以在第一个代码中指出我的错误吗?
答案 0 :(得分:5)
在执行此操作时,有些事情看起来很奇怪:
您有一个异步操作,但是您只需要该值,而无需实际等待操作完成。尝试这样的事情:
module.exports = new Promise ((resolve, reject) => {
mysql.query('SELECT id, name FROM news', (error, results) => {
if (error)
reject({error: `DB Error: ${error.code} (${error.sqlState})`})
resolve(JSON.parse(JSON.stringify(results)));
});
});
然后获取新闻:
var getNewsAsync = require('./news')
getNewsAsync.then(news => console.log(news))
如果您实际上将mysql
库与async / await结合使用,将会更简洁/更短。
更新:
使用Node 8 and above you should be able to promisify和mySQL
lib方法。尽管可能有更好的npm选项可以使它起作用。这是未试用版本:
const mysql = require('mysql');
const util = require('util');
const conn = mysql.createConnection({yourHOST/USER/PW/DB});
const query = util.promisify(conn.query).bind(conn);
module.exports = async () => {
try {return await query('SELECT id, name FROM news')} finally {conn.end()}
}
要获取新闻:
var getNewsAsync = require('./news')
console.log(await getNewsAsync())