在node.js中调用多个异步函数的正确过程

Correct procedure to call multiple asynchronous functions in node.js

本文关键字:函数 过程 异步 js node 调用      更新时间:2023-09-26

我有一个要求,我需要从表1中获取记录并存储在redis缓存中,一旦redis缓存完成存储,就获取表2的记录并存储到redis缓存。因此有4个异步函数。

步骤:

  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...");
                }
            });
        }
    });    
}

创建两个参数化函数。一个用于检索,一个用于存储。

然后答应他们两个。

然后写:

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需要一个polyfill。

以下是Ben Aston使用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

或者,如果你想使用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 
})