### Install async-es for ES Module usage Source: https://github.com/caolan/async/blob/master/docs/v3/index.html Shows how to install the `async-es` package for using Async.js with modern ES Modules. It includes examples of importing the entire library or specific functions. ```bash $ npm install async-es import waterfall from 'async-es/waterfall'; import async from 'async-es'; ``` -------------------------------- ### Example Usage Source: https://github.com/caolan/async/blob/master/docs/v3/module-ControlFlow.html An example demonstrating how to create and use an async queue. ```APIDOC ## Example Usage ### Description An example demonstrating how to create and use an async queue. ### Code Example ```javascript const q = async.queue(worker, 2) q.push(item1) q.push(item2) q.push(item3) // queues are iterable, spread into an array to inspect const items = [...q] // [item1, item2, item3] // or use for of for (let item of q) { console.log(item) } q.drain(() => { console.log('all done') }) // or await q.drain() ``` ``` -------------------------------- ### Install Async.js using npm Source: https://github.com/caolan/async/blob/master/docs/v3/index.html Provides instructions for installing the Async.js library using the npm package manager. It also shows how to require the entire library or individual methods. ```bash $ npm i async var async = require("async"); var waterfall = require("async/waterfall"); var map = require("async/map"); ``` -------------------------------- ### Install TypeScript Definitions for Async Source: https://github.com/caolan/async/blob/master/docs/v3/index.html Installs the necessary type definitions for using Async with TypeScript. Requires a development dependency installation. ```bash npm i -D @types/async ``` -------------------------------- ### Install Async.js using npm Source: https://github.com/caolan/async/blob/master/intro.md Installs the async library using npm, a package manager for Node.js. This is the standard way to add the library to your project for server-side or build-tool-based development. ```bash npm i async ``` -------------------------------- ### Install Minami JSDoc Template Source: https://github.com/caolan/async/blob/master/support/jsdoc/theme/README.md This command installs the Minami JSDoc template as a development dependency for your project using npm. ```bash $ npm install --save-dev minami ``` -------------------------------- ### Async Map File Size Example (JavaScript) Source: https://github.com/caolan/async/blob/master/docs/v3/module-Collections.html Demonstrates how to use async.map to get the sizes of multiple files asynchronously. It shows implementations using callbacks, Promises, and async/await, including error handling for non-existent files. ```javascript const fs = require('fs'); const async = require('async'); // file1.txt is a file that is 1000 bytes in size // file2.txt is a file that is 2000 bytes in size // file3.txt is a file that is 3000 bytes in size // file4.txt does not exist const fileList = ['file1.txt','file2.txt','file3.txt']; const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; // asynchronous function that returns the file size in bytes function getFileSizeInBytes(file, callback) { fs.stat(file, function(err, stat) { if (err) { return callback(err); } callback(null, stat.size); }); } // Using callbacks async.map(fileList, getFileSizeInBytes, function(err, results) { if (err) { console.log(err); } else { console.log(results); // results is now an array of the file size in bytes for each file, e.g. // [ 1000, 2000, 3000] } }); // Error Handling async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { if (err) { console.log(err); // [ Error: ENOENT: no such file or directory ] } else { console.log(results); } }); // Using Promises async.map(fileList, getFileSizeInBytes) .then( results => { console.log(results); // results is now an array of the file size in bytes for each file, e.g. // [ 1000, 2000, 3000] }).catch( err => { console.log(err); }); // Error Handling async.map(withMissingFileList, getFileSizeInBytes) .then( results => { console.log(results); }).catch( err => { console.log(err); // [ Error: ENOENT: no such file or directory ] }); // Using async/await (async () => { try { let results = await async.map(fileList, getFileSizeInBytes); console.log(results); // results is now an array of the file size in bytes for each file, e.g. // [ 1000, 2000, 3000] } catch (err) { console.log(err); } })(); // Error Handling (async () => { try { let results = await async.map(withMissingFileList, getFileSizeInBytes); console.log(results); } catch (err) { console.log(err); // [ Error: ENOENT: no such file or directory ] } })(); ``` -------------------------------- ### Async Queue Usage Example Source: https://github.com/caolan/async/blob/master/docs/v3/docs.html Demonstrates how to create an async queue, push tasks, iterate over pending tasks, and handle the drain event. The queue manages concurrency and task processing. ```javascript const q = async.queue(worker, 2) q.push(item1) q.push(item2) q.push(item3) // queues are iterable, spread into an array to inspect const items = [...q] // [item1, item2, item3] // or use for of for (let item of q) { console.log(item) } q.drain(() => { console.log('all done') }) // or await q.drain() ``` -------------------------------- ### Async Each Iteration Example (JavaScript) Source: https://github.com/caolan/async/blob/master/docs/v2/docs.html Demonstrates the use of async.each for iterating over a collection of files, performing an asynchronous save operation for each. It includes error handling and provides an alternative example with custom processing logic within the iteration. ```javascript // assuming openFiles is an array of file names and saveFile is a function // to save the modified contents of that file: async.each(openFiles, saveFile, function(err){ // if any of the saves produced an error, err would equal that error }); // assuming openFiles is an array of file names async.each(openFiles, function(file, callback) { // Perform operation on file here. console.log('Processing file ' + file); if( file.length > 32 ) { console.log('This file name is too long'); callback('File name too long'); } else { // Do work to process file here console.log('File processed'); callback(); } }, function(err) { // if any of the file processing produced an error, err would equal that error if( err ) { // One of the iterations produced an error. // All processing will now stop. console.log('A file failed to process'); } else { console.log('All files have been processed successfully'); } }); ``` -------------------------------- ### Async.js Series with Async/Await Example Source: https://github.com/caolan/async/blob/master/docs/v3/series.js.html Shows how to use async.series with the async/await syntax for cleaner sequential asynchronous operations. Errors are handled using a try/catch block. ```javascript async () => { try { let results = await async.series([ function(callback) { setTimeout(function() { // do some async task ``` -------------------------------- ### Async.js Series - JavaScript Example Source: https://github.com/caolan/async/blob/master/docs/v2/series.js.html Demonstrates how to use `async.series` with an array of functions. Each function is executed sequentially, and results are collected. If any function returns an error, the series stops immediately. This example shows basic task execution and result collection. ```javascript import async from './async'; // Assuming async is imported or available globally async.series([ function(callback) { // do some stuff ... callback(null, 'one'); }, function(callback) { // do some more stuff ... callback(null, 'two'); } ], // optional callback function(err, results) { // results is now equal to ['one', 'two'] }); ``` -------------------------------- ### Async Auto with Async/Await Example Source: https://github.com/caolan/async/blob/master/docs/v3/auto.js.html Illustrates the usage of `async.auto` with modern `async/await` syntax, providing a cleaner and more synchronous-looking way to handle asynchronous task dependencies. Includes try-catch for error handling. ```javascript async () => { try { let results = await async.auto({ get_data: function(callback) { // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback) { // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, write_file: ['get_data', 'make_folder', function(results, callback) { // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }], email_link: ['write_file', function(results, callback) { // once the file is written let's email a link to it... callback(null, {'file':results.write_file, 'email':'user@example.com'}); }] }); console.log('results = ', results); // results = { // get_data: ['data', 'converted to array'] // make_folder; 'folder', // write_file: 'filename' // email_link: { file: 'filename', email: 'user@example.com' } // } } catch (err) { console.log(err); } } ``` -------------------------------- ### Async autoInject Example Source: https://github.com/caolan/async/blob/master/docs/v2/module-ControlFlow.html Demonstrates how to use async.autoInject for defining and running a series of asynchronous tasks with dependencies. It handles minified parameter names by allowing explicit dependency declaration. ```javascript // The example from `auto` can be rewritten as follows: async.autoInject({ get_data: function(callback) { // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback) { // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, write_file: function(get_data, make_folder, callback) { // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }, email_link: function(write_file, callback) { // once the file is written let's email a link to it... // write_file contains the filename returned by write_file. callback(null, {'file':write_file, 'email':'user@example.com'}); } }, function(err, results) { console.log('err = ', err); console.log('email_link = ', results.email_link); }); // If you are using a JS minifier that mangles parameter names, `autoInject` // will not work with plain functions, since the parameter names will be // collapsed to a single letter identifier. To work around this, you can // explicitly specify the names of the parameters your task function needs // in an array, similar to Angular.js dependency injection. // This still has an advantage over plain `auto`, since the results a task // depends on are still spread into arguments. async.autoInject({ //... write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { callback(null, 'filename'); }], email_link: ['write_file', function(write_file, callback) { callback(null, {'file':write_file, 'email':'user@example.com'}); }] //... }, function(err, results) { console.log('err = ', err); console.log('email_link = ', results.email_link); }); ``` -------------------------------- ### async.parallel Examples Source: https://github.com/caolan/async/blob/master/docs/v3/module-ControlFlow.html Demonstrates how to use async.parallel with callbacks, Promises, and async/await, for both array and object task inputs. ```APIDOC ## async.parallel Examples ### Description Examples showing the usage of `async.parallel` with callbacks, Promises, and async/await syntax. Tasks can be provided as an array or an object. ### Method (Static method of the async library) ### Endpoint N/A (JavaScript function) ### Parameters #### Request Body (for task functions within the array/object) - **callback** (function) - Required - A callback function to be called when the task is completed. It accepts `(err, result)`. ### Request Example (Array with Callbacks) ```javascript async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ], function(err, results) { // results is equal to ['one','two'] }); ``` ### Request Example (Object with Callbacks) ```javascript async.parallel({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { callback(null, 2); }, 100); } }, function(err, results) { // results is equal to: { one: 1, two: 2 } }); ``` ### Request Example (Array with Promises) ```javascript async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ]).then(results => { // results is equal to ['one','two'] }).catch(err => { // handle error }); ``` ### Request Example (Object with Promises) ```javascript async.parallel({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { callback(null, 2); }, 100); } }).then(results => { // results is equal to: { one: 1, two: 2 } }).catch(err => { // handle error }); ``` ### Request Example (Array with async/await) ```javascript async () => { try { let results = await async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ]); // results is equal to ['one','two'] } catch (err) { // handle error } } ``` ### Request Example (Object with async/await) ```javascript async () => { try { let results = await async.parallel({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { callback(null, 2); }, 100); } }); // results is equal to: { one: 1, two: 2 } } catch (err) { // handle error } } ``` ### Response #### Success Response - **results** (Array | Object) - An array or object containing the results from each task, preserving the order or keys provided. #### Response Example (Array) ```json [ "one", "two" ] ``` #### Response Example (Object) ```json { "one": 1, "two": 2 } ``` ``` -------------------------------- ### Async.js Usage in Browser Environment Source: https://github.com/caolan/async/blob/master/docs/v2/index.html Demonstrates how to include and use the async.js library within an HTML page for browser-based JavaScript applications. Includes script tags for loading the library and an example of using async.map. ```html ``` -------------------------------- ### Install async-es for ES Modules Source: https://github.com/caolan/async/blob/master/intro.md Installs the 'async-es' package, which provides Async.js as a collection of purely ES2015 modules. This is suitable for modern bundlers like Webpack or Rollup that support the 'module' field in package.json. ```bash npm install async-es ``` -------------------------------- ### Import Async ES Modules Source: https://github.com/caolan/async/blob/master/docs/v2/index.html Demonstrates how to import specific functions or the entire Async library when using ES Modules. This requires installing the `async-es` package. It showcases importing `waterfall` and the main `async` object. ```javascript import waterfall from 'async-es/waterfall'; import async from 'async-es'; ``` -------------------------------- ### Async.js Series with Callbacks Example Source: https://github.com/caolan/async/blob/master/docs/v3/series.js.html Demonstrates the usage of async.series with an array of asynchronous functions using traditional callbacks. Tasks run sequentially, and the final callback receives results or an error. ```javascript async.series([ function(callback) { setTimeout(function() { // do some async task callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { // then do another async task callback(null, 'two'); }, 100); } ], function(err, results) { console.log(results); // results is equal to ['one','two'] }); // an example using objects instead of arrays async.series({ one: function(callback) { setTimeout(function() { // do some async task callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { // then do another async task callback(null, 2); }, 100); } }, function(err, results) { console.log(results); // results is equal to: { one: 1, two: 2 } }); ``` -------------------------------- ### Async Auto with Callbacks Example Source: https://github.com/caolan/async/blob/master/docs/v3/auto.js.html Demonstrates using `async.auto` with traditional callbacks to manage a series of dependent asynchronous operations. Tasks are defined with their dependencies, and results are passed sequentially. ```javascript async.auto({ get_data: ['data', 'converted to array'], make_folder: 'folder', write_file: ['get_data', 'make_folder', function(results, callback) { // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }], email_link: ['write_file', function(results, callback) { // once the file is written let's email a link to it... callback(null, {'file':results.write_file, 'email':'user@example.com'}); }] }).then(results => { console.log('results = ', results); // results = { // get_data: ['data', 'converted to array'] // make_folder; 'folder', // write_file: 'filename' // email_link: { file: 'filename', email: 'user@example.com' } // } }).catch(err => { console.log('err = ', err); }); ``` -------------------------------- ### Async.js autoInject Example Usage Source: https://github.com/caolan/async/blob/master/docs/v2/autoInject.js.html An example demonstrating the usage of `async.autoInject` to define a series of asynchronous tasks with interdependencies. The example shows how task results are injected as arguments into dependent tasks, making the code more readable. It also touches upon handling minified parameter names by using an array syntax for task definitions. ```javascript // The example from `auto` can be rewritten as follows: async.autoInject({ get_data: function(callback) { // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback) { // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, write_file: function(get_data, make_folder, callback) { // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }, email_link: function(write_file, callback) { // once the file is written let's email a link to it... // write_file contains the filename returned by write_file. callback(null, {'file':write_file, 'email':'user@example.com'}); } }, function(err, results) { console.log('err = ', err); console.log('email_link = ', results.email_link); }); // If you are using a JS minifier that mangles parameter names, `autoInject` // will not work with plain functions, since the parameter names will be // collapsed to a single letter identifier. To work around this, you can // explicitly specify the names of the parameters your task function needs // in an array, similar to Angular.js dependency injection. // This still has an advantage over plain `auto`, since the results a task // depends on are still spread into arguments. async.autoInject({ //... write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { ``` -------------------------------- ### Require Async.js in Node.js Source: https://github.com/caolan/async/blob/master/intro.md Demonstrates how to import the entire async library into a Node.js project after installation. This allows access to all of its asynchronous utility functions. ```javascript var async = require("async"); ``` -------------------------------- ### Async.js auto() with Promises Source: https://github.com/caolan/async/blob/master/docs/v3/auto.js.html Illustrates the use of the `async.auto` function with Promises for managing asynchronous tasks. This example shows how tasks can return Promises, and how `async.auto` handles their resolution or rejection. ```javascript async.auto({ get_data: function(callback) { console.log('in get_data'); // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback) { console.log('in make_folder'); // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, // ... other tasks can be defined here, potentially returning promises }); ``` -------------------------------- ### Async EachOf Iteration Example (JavaScript) Source: https://github.com/caolan/async/blob/master/docs/v2/docs.html Demonstrates the usage of async.eachOf for iterating over an object or array, passing both the item and its key (or index) to the asynchronous iteratee function. This is useful when the key is needed for processing, such as in reading configuration files. ```javascript import eachOf from 'async/eachOf'; var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; var configs = {}; async.forEachOf(obj, function (value, key, callback) { fs.readFile(__dirname + value, "utf8", function (err, data) { if (err) return callback(err); try { configs[key] = JSON.parse(data); } catch (e) { return callback(e); } callback(); }); }, function (err) { if (err) console.error(err.message); // configs is now a map of JSON data doSomethingWith(configs); }); ``` -------------------------------- ### Async Retry with Default Options Source: https://github.com/caolan/async/blob/master/docs/v3/docs.html This example uses `async.retry` with only the task and callback provided, relying on the default options. By default, it will retry 5 times with no delay between attempts. ```javascript async.retry(apiMethod, function(err, result) { // do something with the result }); ``` -------------------------------- ### Use Async.js in the Browser Source: https://github.com/caolan/async/blob/master/intro.md Provides an example of how to include and use the async library in a web browser via a script tag. It shows a common pattern of using `async.map` to process data asynchronously and update the UI. ```html ``` -------------------------------- ### Async.js Series with Promises Example Source: https://github.com/caolan/async/blob/master/docs/v3/series.js.html Illustrates using async.series with Promises for sequential asynchronous task execution. The `.then()` block handles successful completion with results, while `.catch()` handles any errors. ```javascript async.series([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ]).then(results => { console.log(results); // results is equal to ['one','two'] }).catch(err => { console.log(err); }); // an example using an object instead of an arrayasync.series({ one: function(callback) { setTimeout(function() { // do some async task callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { // then do another async task callback(null, 2); }, 100); } }).then(results => { console.log(results); // results is equal to: { one: 1, two: 2 } }).catch(err => { console.log(err); }); ``` -------------------------------- ### Async Waterfall Example Source: https://github.com/caolan/async/blob/master/docs/v2/module-Utils.html Demonstrates the usage of async.waterfall to execute a series of asynchronous functions in sequence. Each function receives the result of the previous one. Supports passing initial values or using functions like fs.readFile. ```javascript async.waterfall([ async.constant(42), function (value, next) { // value === 42 }, //... ], callback); async.waterfall([ async.constant(filename, "utf8"), fs.readFile, function (fileData, next) { //... } //... ], callback); ``` -------------------------------- ### Async Waterfall and Auto Example using JavaScript Source: https://github.com/caolan/async/blob/master/docs/v3/module-Utils.html Demonstrates the use of async.waterfall for sequential task execution and async.auto for parallel task execution with dependencies. These patterns are common for managing complex asynchronous workflows. ```javascript async.waterfall([ async.constant(42), function (value, next) { // value === 42 }, //... ], callback); async.waterfall([ async.constant(filename, "utf8"), fs.readFile, function (fileData, next) { //... } //... ], callback); async.auto({ hostname: async.constant("https://server.net/"), port: findFreePort, launchServer: ["hostname", "port", function (options, cb) { startServer(options, cb); }], //... }, callback); ``` -------------------------------- ### Async Map Example with Node.js fs.stat Source: https://github.com/caolan/async/blob/master/docs/v2/index.html Demonstrates the usage of `async.map` to process an array of file paths. It applies the `fs.stat` function to each file asynchronously and collects the results. Assumes the `fs` module is available (typically in Node.js). ```javascript async.map(['file1','file2','file3'], fs.stat, function(err, results) { // results is now an array of stats for each file }); ``` -------------------------------- ### Async Auto Example Source: https://github.com/caolan/async/blob/master/docs/v2/module-Utils.html Illustrates async.auto for defining tasks that can be run in parallel, with dependencies managed. Tasks are defined in an object where keys are task names and values are either the task function or an array specifying dependencies and the task function. ```javascript async.auto({ hostname: async.constant("https://server.net/"), port: findFreePort, launchServer: ["hostname", "port", function (options, cb) { startServer(options, cb); }], //... }, callback); ``` -------------------------------- ### Async.js reduce Example Source: https://github.com/caolan/async/blob/master/docs/v2/module-Collections.html Provides an example of using async.reduce to perform an asynchronous reduction on a collection. It starts with an initial memoized value and applies an asynchronous iterator function to each element, accumulating a single result. This is useful when each step of the reduction involves asynchronous operations. The function operates in series. ```javascript async.reduce([1,2,3], 0, function(memo, item, callback) { // pointless async: process.nextTick(function() { callback(null, memo + item) }); }, function(err, result) { // result is now equal to the last value of memo, which is 6 }); ``` -------------------------------- ### Sort files by size using async.sortBy with callbacks Source: https://github.com/caolan/async/blob/master/docs/v3/docs.html This example demonstrates how to sort an array of file names by their size in ascending order using `async.sortBy` with traditional callbacks. It defines a helper function `getFileSizeInBytes` to asynchronously get file sizes and passes it to `async.sortBy`. ```javascript // bigfile.txt is a file that is 251100 bytes in size // mediumfile.txt is a file that is 11000 bytes in size // smallfile.txt is a file that is 121 bytes in size // asynchronous function that returns the file size in bytes function getFileSizeInBytes(file, callback) { fs.stat(file, function(err, stat) { if (err) { return callback(err); } callback(null, stat.size); }); } // Using callbacks async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, function(err, results) { if (err) { console.log(err); } else { console.log(results); // results is now the original array of files sorted by // file size (ascending by default), e.g. // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] } } ); // By modifying the callback parameter the // sorting order can be influenced: // ascending order async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { if (getFileSizeErr) return callback(getFileSizeErr); callback(null, fileSize); }); }, function(err, results) { if (err) { console.log(err); } else { console.log(results); // results is now the original array of files sorted by // file size (ascending by default), e.g. // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] } } ); // descending order async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { if (getFileSizeErr) { return callback(getFileSizeErr); } callback(null, fileSize * -1); }); }, function(err, results) { if (err) { console.log(err); } else { console.log(results); // results is now the original array of files sorted by // file size (ascending by default), e.g. // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] } } ); // Error handling async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, function(err, results) { if (err) { console.log(err); // [ Error: ENOENT: no such file or directory ] } else { console.log(results); } } ); ``` -------------------------------- ### Example JSDoc Configuration Source: https://github.com/caolan/async/blob/master/support/jsdoc/theme/README.md This comprehensive JSON configuration file outlines various settings for JSDoc, including tag definitions, source file inclusion/exclusion patterns, plugin usage, template options, and output destination. It specifically configures the Minami template. ```json { "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc"] }, "source": { "include": ["lib", "package.json", "README.md"], "includePattern": ".js$", "excludePattern": "(node_modules/|docs)" }, "plugins": [ "plugins/markdown" ], "templates": { "cleverLinks": false, "monospaceLinks": true }, "opts": { "destination": "./docs/", "encoding": "utf8", "private": true, "recurse": true, "template": "./node_modules/minami" } } ``` -------------------------------- ### Async Utility: apply Source: https://github.com/caolan/async/blob/master/docs/v3/docs.html Documentation for the `async.apply` utility function. ```APIDOC ## Async Utility: apply ### Description Creates a continuation function with some arguments already applied. Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply. ### Method `async.apply(fn)` ### Parameters - **`fn`** (function) - The function to apply arguments to. ### Returns - {function} A new function with the arguments partially applied. ### Request Example ```javascript import apply from 'async/apply'; function sum(a, b, c) { return a + b + c; } const add5 = apply(sum, 5); const result = add5(10, 20); // result will be 35 (5 + 10 + 20) console.log(result); ``` ### Response Example ```json { "result": 35 } ``` ``` -------------------------------- ### async.retry Source: https://github.com/caolan/async/blob/master/docs/v2/docs.html Attempts to get a successful response from a task multiple times before returning an error. ```APIDOC ## async.retry ### Description Attempts to get a successful response from `task` no more than `opts.times` times before returning an error. If the task is successful, the `callback` will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt. ### Method Static ### Endpoint (static) retry(optsopt, task, callbackopt) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **opts** (Object | number) - Optional. Can be an object with `times` and `interval` or a number specifying the number of times to retry. - `times` (number) - The number of attempts to make. Defaults to 5. - `interval` (number | function) - The time to wait between retries in milliseconds. Defaults to 0. Can be a function of the retry count. - `errorFilter` (function) - An optional synchronous function invoked on erroneous result. If it returns `true`, retries continue; otherwise, the retry flow aborts. - **task** ([AsyncFunction](global.html)) - An async function to retry. Invoked with (callback). - **callback** (function) - Optional. Called when the task succeeds or after the final failed attempt. Receives (err, results). ### Request Example ```javascript // Try calling apiMethod 3 times async.retry(3, apiMethod, function(err, result) { /* do something */ }); // Try calling apiMethod 3 times, waiting 200 ms between retries async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { /* do something */ }); // Try calling apiMethod 10 times with exponential backoff async.retry({ times: 10, interval: function(retryCount) { return 50 * Math.pow(2, retryCount); } }, apiMethod, function(err, result) { /* do something */ }); // Try calling apiMethod only when error condition satisfies async.retry({ errorFilter: function(err) { return err.message === 'Temporary error'; } }, apiMethod, function(err, result) { /* do something */ }); ``` ### Response #### Success Response (200) - **result** (any) - The result of the successful task. #### Error Response - **err** (Error) - The error from the final failed attempt. - **result** (any) - The result from the final failed attempt. #### Response Example ```json { "result": "Success" } ``` ``` -------------------------------- ### Async Queue Initialization and Basic Usage Source: https://github.com/caolan/async/blob/master/docs/v3/module-ControlFlow.html Demonstrates how to initialize an async queue with a worker function and a concurrency limit, push tasks to it, and handle the 'drain' event, both with a callback and using promises. ```javascript const q = async.queue(worker, 2) q.push(item1) q.push(item2) q.push(item3) q.drain(() => { console.log('all done') }) // or await q.drain() ``` -------------------------------- ### async.retry Source: https://github.com/caolan/async/blob/master/docs/v3/docs.html Attempts to get a successful response from a task a specified number of times before returning an error. It can handle custom intervals and error filtering. ```APIDOC ## async.retry ### Description Attempts to get a successful response from `task` no more than `times` times before returning an error. If the task is successful, the `callback` will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt. ### Method Static ### Endpoint N/A (Client-side library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **opts** (Object | number) - Optional. Can be either an object with `times` and `interval` or a number. Defaults to 5. - `times` (number) - The number of attempts to make before giving up. The default is `5`. - `interval` (number | function) - The time to wait between retries, in milliseconds. The default is `0`. Can also be a function of the retry count. - `errorFilter` (function) - An optional synchronous function that is invoked on erroneous result. If it returns `true` the retry attempts will continue; if the function returns `false` the retry flow is aborted. Invoked with (err). - **task** (AsyncFunction) - An async function to retry. Invoked with (callback). - **callback** (function) - Optional. Called when the task has succeeded, or after the final failed attempt. Receives (err, results). ### Request Example ```javascript // Try calling apiMethod 3 times async.retry(3, apiMethod, function(err, result) { // do something with the result }); // Try calling apiMethod 3 times, waiting 200 ms between each retry async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { // do something with the result }); // Try calling apiMethod 10 times with exponential backoff async.retry({ times: 10, interval: function(retryCount) { return 50 * Math.pow(2, retryCount); } }, apiMethod, function(err, result) { // do something with the result }); // Try calling apiMethod only when error condition satisfies async.retry({ errorFilter: function(err) { return err.message === 'Temporary error'; // only retry on a specific error } }, apiMethod, function(err, result) { // do something with the result }); ``` ### Response #### Success Response (200) - **result** (any) - The result of the successful task. #### Response Example ```json { "result": "successful data" } ``` #### Error Response (Non-2xx) - **err** (Error) - The error from the final failed attempt. - **result** (any) - The result of the final failed attempt. #### Error Response Example ```json { "err": { "message": "All retries failed." }, "result": "last failed result" } ``` ``` -------------------------------- ### Generate Docs with Minami Template Source: https://github.com/caolan/async/blob/master/support/jsdoc/theme/README.md This command demonstrates how to generate documentation using JSDoc with the Minami template applied. It requires cloning the repository to the JSDoc template directory. ```bash $ jsdoc entry-file.js -t path/to/minami ``` -------------------------------- ### async.cargo API Source: https://github.com/caolan/async/blob/master/docs/v2/docs.html Details the async.cargo function, which creates a cargo object for processing tasks in batches with a specified payload limit. Includes parameters, return values, and an example. ```APIDOC ## async.cargo ### Description Creates a `cargo` object with the specified payload. Tasks added to the cargo will be processed altogether (up to the `payload` limit). If the `worker` is in progress, the task is queued until it becomes available. Once the `worker` has completed some tasks, each callback of those tasks is called. ### Method `async.cargo(worker, payloadopt) → CargoObject` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **worker** (AsyncFunction) - An asynchronous function for processing an array of queued tasks. Invoked with `(tasks, callback)`. * **payloadopt** (number, optional) - An optional integer for determining how many tasks should be processed per round; if omitted, the default is unlimited. ### Request Example ```javascript var cargo = async.cargo(function(tasks, callback) { for (var i=0; i setTimeout(() => callback(null, 'Result A'), 100), (callback) => setTimeout(() => callback(null, 'Result B'), 50) ]; parallel(tasks).then(results => { console.log(results); // Should log ['Result A', 'Result B'] }).catch(err => { console.error(err); }); ``` -------------------------------- ### tryEach Implementation - JavaScript Source: https://github.com/caolan/async/blob/master/docs/v2/tryEach.js.html Implements the `tryEach` control flow function. It runs tasks in series and stops on the first successful completion. Dependencies include `lodash/noop`, `eachSeries`, `wrapAsync`, and `slice`. It takes an array of tasks and an optional callback. The callback receives an error if all tasks fail, or the result from the first successful task. ```javascript import noop from 'lodash/noop'; import eachSeries from './eachSeries'; import wrapAsync from './internal/wrapAsync'; import slice from './internal/slice'; /** * It runs each task in series but stops whenever any of the functions were * successful. If one of the tasks were successful, the `callback` will be * passed the result of the successful task. If all tasks fail, the callback * will be passed the error and result (if any) of the final attempt. * * @name tryEach * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Array|Iterable|Object} tasks - A collection containing functions to * run, each function is passed a `callback(err, result)` it must call on * completion with an error `err` (which can be `null`) and an optional `result` * value. * @param {Function} [callback] - An optional callback which is called when one * of the tasks has succeeded, or all have failed. It receives the `err` and * `result` arguments of the last attempt at completing the `task`. Invoked with * (err, results). * @example * async.tryEach([ * function getDataFromFirstWebsite(callback) { * // Try getting the data from the first website * callback(err, data); * }, * function getDataFromSecondWebsite(callback) { * // First website failed, * // Try getting the data from the backup website * callback(err, data); * } * ], * // optional callback * function(err, results) { * Now do something with the data. * }); * */ export default function tryEach(tasks, callback) { var error = null; var result; callback = callback || noop; eachSeries(tasks, function(task, callback) { wrapAsync(task)(function (err, res/*, ...args*/) { if (arguments.length > 2) { result = slice(arguments, 1); } else { result = res; } error = err; callback(!err); }); }, function () { callback(error, result); }); } ```