【发布时间】:2015-11-20 12:35:22
【问题描述】:
我有一个需求,我需要从表 1 中获取记录并存储在 redis 缓存中,一旦 redis 缓存完成存储,获取表 2 记录并存储在 redis 缓存中。所以有4个异步函数。
步骤:
- 获取表 1 记录
- 存储在 redis 缓存中
- 获取表 2 记录
- 存储在 redis 缓存中
正确的处理方法是什么。
下面是我为处理它而编写的代码。请根据node.js确认其是否正确或任何其他方式处理它
var redis = require("redis");
var client = redis.createClient(6379, 'path', {
auth_pass: 'key'
});
var mysqlConnection = // get the connection from MySQL database
get_Sections1()
function get_Sections1() {
var sql = "select *from employee";
mysqlConnection.query(sql, function (error, results) {
if (error) {
console.log("Error while Sections 1 : " + error);
} else {
client.set("settings1", JSON.stringify(summaryResult), function (err, reply){
if (err) {
console.log("Error during Update of Election : " + err);
} else {
get_Sections2();
}
});
}
});
}
function get_Sections2()
{
var sql = "select *from student";
mysqlConnection.query(sql, function (error, results)
{
if (error)
{
console.log("Error while Sections 2 : " + error);
}
else
{
client.set("settings2", JSON.stringify(summaryResult), function (err, reply)
{
if (err)
{
console.log("Error during Update of Election : " + err);
}
else
{
console.log("Finished the task...");
}
});
}
});
}
【问题讨论】:
-
你可以使用 Promise 来让你的代码更简洁 read more ... 还有几个 Node 的 Promise 模块 ... 只需在 NPM 中搜索它,例如 npmjs.com/package/promise-call
-
感谢 Rafael 的回复,我尝试理解承诺,但不确定。如果你不介意可以用promises转换上面的代码,这样我就可以清楚地理解了。
标签: javascript node.js callback