【问题标题】:Correct procedure to call multiple asynchronous functions in node.js在 node.js 中调用多个异步函数的正确过程
【发布时间】:2015-11-20 12:35:22
【问题描述】:

我有一个需求,我需要从表 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...");
                }
            });
        }
    });    
}

【问题讨论】:

标签: javascript node.js callback


【解决方案1】:

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

然后答应他们俩。

然后写:

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。

【讨论】:

  • 我应该为这个概念安装 promise npm 模块
【解决方案2】:

这是 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 
})

【讨论】:

  • Promise.coroutine 是哪个 ES 规范的一部分?
  • @BenAston none,它是基于生成器的异步函数的垫片。我虽然你知道很多 :) 它使用 bluebirdjs.com/docs/api/promise.coroutine.html 但你可以使用 co 或许多其他提供不同解决方案的库。
  • @BenjaminGruenbaum 是不是类似于c#中的async和await概念
  • 是的,非常相似。
猜你喜欢
  • 2019-01-20
  • 2014-01-30
  • 1970-01-01
  • 2018-01-04
  • 2015-11-04
  • 2015-01-22
  • 2021-05-16
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多