How does async series pass results when you use an embedded asynchronous function?

StackOverflow https://stackoverflow.com/questions/23447048

  •  14-07-2023
  •  | 
  •  

Pergunta

I understand that you can use next(err, result) within an async series worker function to push the result to the final result array like this:

fs = require('fs');
async = require('async');

function readTheFile(next) {
    var result1 = 'something';
    next(null, result1); // <- next is executed
}
function processTheData(next) {
    var result2 = 'something else';
    next(null, result2); 
}
function processFinalResult(err, resultArray) {
    console.log(resultArray); // [ 'something', 'something else' ]
}

async.series(
    [readTheFile,
     processTheData
    ], processFinalResult
);

However, how does result1 get pushed to the final result array if you have the following worker functions:

// file.txt contains 'file data'

fs = require('fs');
async = require('async');

function readTheFile(next) {
    var result1 = 'something'; // <- how does this get to the final result array?
    fs.readFile('file.txt', 'utf8', next); // <- next is only passed.
}
function processTheData(next) {
    var result2 = 'something else';
    next(null, result2);
}
function processFinalResult(err, resultArray) {
    console.log(resultArray); // [ undefined ] length is 1
}

async.series(
    [readTheFile,
     processTheData
    ], processFinalResult
);

I can't call next since that will immediately execute it and instead I'm only allowed to pass the function on as a callback to fs.readFile. How would result1 make it to the final result array?

I'm not figuring it out from reading the docs or the examples.

Foi útil?

Solução

fs.readFile()'s callback takes 2 args (err and data) as follow:

fs.readFile('/etc/passwd', function (err, data) {
   if (err) throw err;
   console.log(data);
});

So when you pass in async.series()'s callback 'next', fs.readFile() calls it as next(err, data) where data will finally be in async's result array. If however, you want to do something to data before you pass to the async's result array, you can do this:

function readTheFile(next) {
    var result1 = 'something';
    fs.readFile('file.txt', 'utf8', function(err, data) {
        if (err) {
            // handle error
        }
        // do some thing with data argument, such as parsing
        // or triming (data = data.trim() for example), or
        // assign it to result1 (result1 = data), then call next()
        next(err, result1);   // this will pass your result1 to async's final array
    }); 
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top