我有一个需求,我需要从表1获取记录并存储在redis缓存中,一旦redis缓存完成存储,获取表2记录并存储在redis缓存中。因此,有4个异步函数。
步骤:
正确的处理程序是什么。
下面是我编写的处理它的代码。请确认它是否是正确的程序,还是按照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...");
}
});
}
});
}发布于 2015-11-20 12:44:22
创建两个参数化函数。一个用于检索,一个用于存储。
那就把他们两个人都搞清楚。
然后写:
return getTableRecords(1)
.then(storeInRedisCache)
.then(getTableRecords.bind(null,2))
.then(storeInRedisCache)
.then(done);为了促进一个函数的实现,类似这样的方法可能会奏效:
var getEmployees = new Promise(function(resolve, reject) {
var sql = "select *from employee";
mysqlConnection.query(sql, function (error, results) {
if (error) {
return reject();
} else {
return resolve(results);
}
});
});如果您使用的是旧版本的NodeJS,您将需要一个Promise的多填充。
发布于 2015-11-20 12:48:14
以下是使用Promise.coroutine假设承诺的Ben解决方案的替代方案:
const doStuff = Promise.coroutine(function*(){
const records = yield getTableRecords(1);
yield storeRecordsInCache(records);
const otherRecords = yield getTableRecords(2);
yield storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath
});
doStuff(); // do all the above, assumes promisification或者,如果您想使用Node中尚未使用的语法(并使用Babel获得支持),您可以这样做:
async function doStuff(){
const records = await getTableRecords(1);
await storeRecordsInCache(records);
const otherRecords = await getTableRecords(2);
await storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath
})https://stackoverflow.com/questions/33826902
复制相似问题