我有一個需求,我需要從表1獲取記錄並存儲在redis緩存中,一旦redis緩存完成存儲,獲取表2記錄並存儲在redis緩存中。所以有4個異步功能。在node.js中調用多個異步函數的正確過程
步驟:
- 獲取表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來使你的代碼更清潔(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)......還有幾個爲節點承諾模塊...只需在NPM中搜索它就像https://www.npmjs.com/package/promise-call – rafaelcastrocouto
感謝拉斐爾的迴應,我嘗試瞭解承諾但不確定。如果你不介意,你可以使用promise來轉換上面的代碼,這樣我就可以清楚地瞭解理解。 – Sharath
@Sharath http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises/和http://bluebirdjs.com/docs/api/promise。 promisifyall.html –