What is a simple async.series implementation?

I have two functions:

function one(next){ Users.find({}, function(err, docs){ if( err) next( err ); } else { next( null ); } }); } function two(next){ Something.find({}, function(err, docs){ if( err) next( err ); } else { next( null ); } }); } 

I can use the asynchronous library:

 async.series( [one, two], function( err ){ ... }); 

Here the callback is called immediately (with a set of errors) if one () returns err. What is a simple, BASIC implementation of async.series? I looked at the async library code (which is fantastic), but it is a library that is designed for a lot of things, and I am having real problems after it.

Can you tell me a simple simple implementation of async.series? Something that it just calls the functions one by one, and - if one of them calls the callback with an error - does it call the final callback with err set?

Thanks...

Merc.

+3
source share
1 answer

One implementation would be something like this:

  function async_series ( fn_list, final_callback ) { // Do we have any more async functions to execute? if (fn_list.length) { // Get the function we want to execute: var fn = fn_list.shift(); // Build a nested callback to process remaining functions: var callback = function () { async_series(fn_list,final_callback); }; // Call the function fn(callback); } else { // Nothing left to process? Then call the final callback: final_callback(); } } 

The code above does not handle the processing of results or errors. To handle errors, we can simply check the error condition in the callback and immediately call the final callback on error:

  function async_series ( fn_list, final_callback ) { if (fn_list.length) { var fn = fn_list.shift(); var callback = function (err) { if (err) { final_callback(err); // error, abort } else { async_series(fn_list,final_callback); } }; fn(callback); } else { final_callback(null); // no errors } } 

Processing of the results can be performed in a similar way by tracing the array of results in closing or passing it to the next async_series call.

Note that the final final callback cannot accept any errors because it arrived there via an if(err)(else)async_series .

+5
source

Source: https://habr.com/ru/post/983454/


All Articles