2015-11-20 70 views
2

我有一個需求,我需要從表1獲取記錄並存儲在redis緩存中,一旦redis緩存完成存儲,獲取表2記錄並存儲在redis緩存中。所以有4個異步功能。在node.js中調用多個異步函數的正確過程

步驟:

  1. 獲取表1的記錄
  2. 存儲在Redis的緩存
  3. 獲取表2的記錄
  4. 存儲在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..."); 
       } 
      }); 
     } 
    });  
} 
+2

你可以使用promise來使你的代碼更清潔(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)......還有幾個爲節點承諾模塊...只需在NPM中搜索它就像https://www.npmjs.com/package/promise-call – rafaelcastrocouto

+0

感謝拉斐爾的迴應,我嘗試瞭解承諾但不確定。如果你不介意,你可以使用promise來轉換上面的代碼,這樣我就可以清楚地瞭解理解。 – Sharath

+0

@Sharath http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises/和http://bluebirdjs.com/docs/api/promise。 promisifyall.html –

回答

2

創建兩個參數化函數。一個用於檢索,一個用於存儲。

然後promisify他們倆。

然後寫:

return getTableRecords(1) 
    .then(storeInRedisCache) 
    .then(getTableRecords.bind(null,2)) 
    .then(storeInRedisCache) 
    .then(done); 

要promisify的功能,這樣的事情可能工作:

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一個填充工具。

+0

應該爲這個概念安裝promise npm模塊 – Sharath

+0

你可以試試https://www.npmjs.com/package/es6-promise-polyfill – Ben

2

下面是使用Promise.coroutine承擔許諾本·阿斯頓的解決方案替代:

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 

另外,如果你想使用語法節點尚未應該(和使用巴貝爾獲得支持),你可以這樣做:

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 
}) 
+0

'Promise.coroutine'是ES規範的一部分嗎? – Ben

+1

@BenAston沒有,這是基於生成器的異步函數的基礎。我雖然知道那麼多:)它使用http://bluebirdjs.com/docs/api/promise.coroutine.html,但您可以使用co或一些其他庫提供不同的解決方案。 –

+0

感謝您的鏈接。 – Ben