Javascript 在node.js中调用多个异步函数的正确过程
我有一个需求,需要从表1中获取记录并存储在redis缓存中,一旦redis缓存完成存储,就需要获取表2记录并存储在redis缓存中。因此有4个异步函数 步骤:Javascript 在node.js中调用多个异步函数的正确过程,javascript,node.js,callback,Javascript,Node.js,Callback,我有一个需求,需要从表1中获取记录并存储在redis缓存中,一旦redis缓存完成存储,就需要获取表2记录并存储在redis缓存中。因此有4个异步函数 步骤: 获取表1记录 存储在redis缓存中 获取表2记录 存储在redis缓存中 正确的处理程序是什么 下面是我为处理它而编写的代码。请确认这是否是正确的程序,或者是否有任何其他方法可以按照node.js进行处理 var redis = require("redis"); var client = redis.createClient(6379
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...");
}
});
}
});
}
创建两个参数化函数。一个用于检索,一个用于存储 然后向他们双方承诺 然后写:
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,则需要使用polyfill作为
Promise
以下是Ben Aston使用Promise的解决方案的替代方案。协同程序
假设承诺:
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
或者,如果您想使用节点中尚未假定的语法(并使用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
})
您可以使用承诺使您的代码更干净。。。还有几个节点的promise模块。。。只需在NPM中搜索它,就像感谢Rafael的回复一样,我试着理解承诺,但不确定。如果您不介意的话,可以使用Promission转换上面的代码,以便我清楚地了解。@Sharath和
Promise.coroutine
是哪个ES规范的一部分?@BenAston none,它是基于生成器的异步函数的垫片。我想你知道很多:)它使用的是co,但你可以使用co或其他一些提供不同解决方案的库。@BenjaminGruenbaum它类似于c#中的async and Wait概念吗?是的,它非常类似。我应该为此概念安装promise npm模块吗