使用async.js系列识别回调数据

Identifying callback data with async.js series

本文关键字:回调 数据 识别 系列 async js 使用      更新时间:2023-09-26

我使用async.js调用3个异步函数,这些函数运行数据库查询,并在下面列出的最后一个函数的results[]参数中返回数据:

async.series([
    function(callback) {
      datasetA.fetch(sqlQueryA).then(function(data) {
        callback(null, data);
      });
    },
    function(callback) {
      datasetB.fetch(sqlQueryB).then(function(data) {
        callback(null, data);
      });
    },
    function(callback) {
      datasetC.fetch(sqlQueryC).then(function(data) {
        callback(null, data);
      });
    }
  ], function(error, results) {
       // Results is array of data containing
       // resultA, resultB, resultC.
  });

我知道所有三个异步函数的结果都在results[]参数中。但是,识别每个查询的结果的最佳方法是什么?我可以想出三种方法:

1。顺序-结果A将位于索引0,结果B位于索引1,结果C位于索引2。async.js文档中显然隐含了这一点,但没有明确说明。

2.在调用async.js callback(null, data)之前修改回调参数:


    async.series([
    function(callback) {
      datasetA.fetch(sqlQuery).then(function(data) {
        data['query'] = 'A';
        callback(null, data);
      });
    },
    function(callback) {
      datasetB.fetch(sqlQuery).then(function(data) {
        data['query'] = 'B';
        callback(null, data);
      });
    },
    function(callback) {
      datasetC.fetch(sqlQuery).then(function(data) {
        data['query'] = 'C';
        callback(null, data);
      });
    }
   ], function(error, results) {
       for (var i=0; i < results.length; i++) {
         // results[i].query will be A, B or C.
       }
    });

3. Inspect the data to determine which query ran.

I don't like 3 because it tightly couples the database schema with code (I only included it for completeness). But I'm less certain about whether 1 or 2 is better. Since the async.js documentation only implies order of results mirrors the order of the asynchronous functions in the array, I'm leaning towards option 2.

Above all else. Why am I even having this problem. Perhaps I'm using the async.js library incorrectly?

The question in the SO post Nodejs async series - pass arguments to next callback provided the answer.

By providing async.series() with an object rather than an array, each asynchronous function becomes an object property and therefore has a key. The key can be used to identify the result.

Applied to my example, it looks like:

async.series({
    A: function(callback){
       datasetA.fetch(sqlQueryA).then(function(data) {
        callback(null, data);
      });
    },
    B: function(callback){
       datasetB.fetch(sqlQueryB).then(function(data) {
        callback(null, data);
      });
    },
    C: function(callback){
        datasetC.fetch(sqlQueryC).then(function(data) {
        callback(null, data);
      });
    }
  },
  function(err, results) {
  // results.A
  // results.B
  // results.C
  });