Commit 8bdf5627 authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'MLAB-667' into 'testing'

Mlab 667

See merge request !151
parents de3756a3 cf9f5af3
Pipeline #6632 passed with stage
in 6 seconds
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _map2 = require('./internal/map.js');
var _map3 = _interopRequireDefault(_map2);
var _eachOfSeries = require('./eachOfSeries.js');
var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
*
* @name mapSeries
* @static
* @memberOf module:Collections
* @method
* @see [async.map]{@link module:Collections.map}
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {AsyncFunction} iteratee - An async function to apply to each item in
* `coll`.
* The iteratee should complete with the transformed item.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. Results is an array of the
* transformed items from the `coll`. Invoked with (err, results).
* @returns {Promise} a promise, if no callback is passed
*/
function mapSeries(coll, iteratee, callback) {
return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(mapSeries, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mapValues;
var _mapValuesLimit = require('./mapValuesLimit.js');
var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
*
* Produces a new Object by mapping each value of `obj` through the `iteratee`
* function. The `iteratee` is called each `value` and `key` from `obj` and a
* callback for when it has finished processing. Each of these callbacks takes
* two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
* passes an error to its callback, the main `callback` (for the `mapValues`
* function) is immediately called with the error.
*
* Note, the order of the keys in the result is not guaranteed. The keys will
* be roughly in the order they complete, (but this is very engine-specific)
*
* @name mapValues
* @static
* @memberOf module:Collections
* @method
* @category Collection
* @param {Object} obj - A collection to iterate over.
* @param {AsyncFunction} iteratee - A function to apply to each value and key
* in `coll`.
* The iteratee should complete with the transformed value as its result.
* Invoked with (value, key, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. `result` is a new object consisting
* of each key from `obj`, with each transformed value on the right-hand side.
* Invoked with (err, result).
* @returns {Promise} a promise, if no callback is passed
* @example
*
* // 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 fileMap = {
* f1: 'file1.txt',
* f2: 'file2.txt',
* f3: 'file3.txt'
* };
*
* const withMissingFileMap = {
* f1: 'file1.txt',
* f2: 'file2.txt',
* f3: 'file4.txt'
* };
*
* // asynchronous function that returns the file size in bytes
* function getFileSizeInBytes(file, key, callback) {
* fs.stat(file, function(err, stat) {
* if (err) {
* return callback(err);
* }
* callback(null, stat.size);
* });
* }
*
* // Using callbacks
* async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {
* if (err) {
* console.log(err);
* } else {
* console.log(result);
* // result is now a map of file size in bytes for each file, e.g.
* // {
* // f1: 1000,
* // f2: 2000,
* // f3: 3000
* // }
* }
* });
*
* // Error handling
* async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {
* if (err) {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* } else {
* console.log(result);
* }
* });
*
* // Using Promises
* async.mapValues(fileMap, getFileSizeInBytes)
* .then( result => {
* console.log(result);
* // result is now a map of file size in bytes for each file, e.g.
* // {
* // f1: 1000,
* // f2: 2000,
* // f3: 3000
* // }
* }).catch (err => {
* console.log(err);
* });
*
* // Error Handling
* async.mapValues(withMissingFileMap, getFileSizeInBytes)
* .then( result => {
* console.log(result);
* }).catch (err => {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* });
*
* // Using async/await
* async () => {
* try {
* let result = await async.mapValues(fileMap, getFileSizeInBytes);
* console.log(result);
* // result is now a map of file size in bytes for each file, e.g.
* // {
* // f1: 1000,
* // f2: 2000,
* // f3: 3000
* // }
* }
* catch (err) {
* console.log(err);
* }
* }
*
* // Error Handling
* async () => {
* try {
* let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);
* console.log(result);
* }
* catch (err) {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* }
* }
*
*/
function mapValues(obj, iteratee, callback) {
return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _eachOfLimit = require('./internal/eachOfLimit.js');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
var _once = require('./internal/once.js');
var _once2 = _interopRequireDefault(_once);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
* time.
*
* @name mapValuesLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.mapValues]{@link module:Collections.mapValues}
* @category Collection
* @param {Object} obj - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {AsyncFunction} iteratee - A function to apply to each value and key
* in `coll`.
* The iteratee should complete with the transformed value as its result.
* Invoked with (value, key, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. `result` is a new object consisting
* of each key from `obj`, with each transformed value on the right-hand side.
* Invoked with (err, result).
* @returns {Promise} a promise, if no callback is passed
*/
function mapValuesLimit(obj, limit, iteratee, callback) {
callback = (0, _once2.default)(callback);
var newObj = {};
var _iteratee = (0, _wrapAsync2.default)(iteratee);
return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => {
_iteratee(val, key, (err, result) => {
if (err) return next(err);
newObj[key] = result;
next(err);
});
}, err => callback(err, newObj));
}
exports.default = (0, _awaitify2.default)(mapValuesLimit, 4);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mapValuesSeries;
var _mapValuesLimit = require('./mapValuesLimit.js');
var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
*
* @name mapValuesSeries
* @static
* @memberOf module:Collections
* @method
* @see [async.mapValues]{@link module:Collections.mapValues}
* @category Collection
* @param {Object} obj - A collection to iterate over.
* @param {AsyncFunction} iteratee - A function to apply to each value and key
* in `coll`.
* The iteratee should complete with the transformed value as its result.
* Invoked with (value, key, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. `result` is a new object consisting
* of each key from `obj`, with each transformed value on the right-hand side.
* Invoked with (err, result).
* @returns {Promise} a promise, if no callback is passed
*/
function mapValuesSeries(obj, iteratee, callback) {
return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = memoize;
var _setImmediate = require('./internal/setImmediate.js');
var _setImmediate2 = _interopRequireDefault(_setImmediate);
var _initialParams = require('./internal/initialParams.js');
var _initialParams2 = _interopRequireDefault(_initialParams);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Caches the results of an async function. When creating a hash to store
* function results against, the callback is omitted from the hash and an
* optional hash function can be used.
*
* **Note: if the async function errs, the result will not be cached and
* subsequent calls will call the wrapped function.**
*
* If no hash function is specified, the first argument is used as a hash key,
* which may work reasonably if it is a string or a data type that converts to a
* distinct string. Note that objects and arrays will not behave reasonably.
* Neither will cases where the other arguments are significant. In such cases,
* specify your own hash function.
*
* The cache of results is exposed as the `memo` property of the function
* returned by `memoize`.
*
* @name memoize
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {AsyncFunction} fn - The async function to proxy and cache results from.
* @param {Function} hasher - An optional function for generating a custom hash
* for storing results. It has all the arguments applied to it apart from the
* callback, and must be synchronous.
* @returns {AsyncFunction} a memoized version of `fn`
* @example
*
* var slow_fn = function(name, callback) {
* // do something
* callback(null, result);
* };
* var fn = async.memoize(slow_fn);
*
* // fn can now be used as if it were slow_fn
* fn('some name', function() {
* // callback
* });
*/
function memoize(fn, hasher = v => v) {
var memo = Object.create(null);
var queues = Object.create(null);
var _fn = (0, _wrapAsync2.default)(fn);
var memoized = (0, _initialParams2.default)((args, callback) => {
var key = hasher(...args);
if (key in memo) {
(0, _setImmediate2.default)(() => callback(null, ...memo[key]));
} else if (key in queues) {
queues[key].push(callback);
} else {
queues[key] = [callback];
_fn(...args, (err, ...resultArgs) => {
// #1465 don't memoize if an error occurred
if (!err) {
memo[key] = resultArgs;
}
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i](err, ...resultArgs);
}
});
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _setImmediate = require('./internal/setImmediate.js');
/**
* Calls `callback` on a later loop around the event loop. In Node.js this just
* calls `process.nextTick`. In the browser it will use `setImmediate` if
* available, otherwise `setTimeout(callback, 0)`, which means other higher
* priority events may precede the execution of `callback`.
*
* This is used internally for browser-compatibility purposes.
*
* @name nextTick
* @static
* @memberOf module:Utils
* @method
* @see [async.setImmediate]{@link module:Utils.setImmediate}
* @category Util
* @param {Function} callback - The function to call on a later loop around
* the event loop. Invoked with (args...).
* @param {...*} args... - any number of additional arguments to pass to the
* callback on the next tick.
* @example
*
* var call_order = [];
* async.nextTick(function() {
* call_order.push('two');
* // call_order now equals ['one','two']
* });
* call_order.push('one');
*
* async.setImmediate(function (a, b, c) {
* // a, b, and c equal 1, 2, and 3
* }, 1, 2, 3);
*/
var _defer; /* istanbul ignore file */
if (_setImmediate.hasNextTick) {
_defer = process.nextTick;
} else if (_setImmediate.hasSetImmediate) {
_defer = setImmediate;
} else {
_defer = _setImmediate.fallback;
}
exports.default = (0, _setImmediate.wrap)(_defer);
module.exports = exports['default'];
\ No newline at end of file
{
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
"version": "3.2.4",
"main": "dist/async.js",
"author": "Caolan McMahon",
"homepage": "https://caolan.github.io/async/",
"repository": {
"type": "git",
"url": "https://github.com/caolan/async.git"
},
"bugs": {
"url": "https://github.com/caolan/async/issues"
},
"keywords": [
"async",
"callback",
"module",
"utility"
],
"devDependencies": {
"@babel/eslint-parser": "^7.16.5",
"babel-core": "^6.26.3",
"babel-minify": "^0.5.0",
"babel-plugin-add-module-exports": "^1.0.4",
"babel-plugin-istanbul": "^6.1.1",
"babel-plugin-syntax-async-generators": "^6.13.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-preset-es2015": "^6.3.13",
"babel-preset-es2017": "^6.22.0",
"babel-register": "^6.26.0",
"babelify": "^10.0.0",
"benchmark": "^2.1.1",
"bluebird": "^3.4.6",
"browserify": "^17.0.0",
"chai": "^4.2.0",
"cheerio": "^0.22.0",
"es6-promise": "^4.2.8",
"eslint": "^8.6.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"fs-extra": "^10.0.0",
"jsdoc": "^3.6.2",
"karma": "^6.3.12",
"karma-browserify": "^8.1.0",
"karma-firefox-launcher": "^2.1.2",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.0",
"karma-safari-launcher": "^1.0.0",
"mocha": "^6.1.4",
"native-promise-only": "^0.8.0-a",
"nyc": "^15.1.0",
"rollup": "^2.66.1",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-npm": "^2.0.0",
"rsvp": "^4.8.5",
"semver": "^7.3.5",
"yargs": "^17.3.1"
},
"scripts": {
"coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert",
"jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js",
"lint": "eslint --fix .",
"mocha-browser-test": "karma start",
"mocha-node-test": "mocha",
"mocha-test": "npm run mocha-node-test && npm run mocha-browser-test",
"test": "npm run lint && npm run mocha-node-test"
},
"license": "MIT",
"nyc": {
"exclude": [
"test"
]
},
"module": "dist/async.mjs"
}
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parallel;
var _eachOf = require('./eachOf.js');
var _eachOf2 = _interopRequireDefault(_eachOf);
var _parallel2 = require('./internal/parallel.js');
var _parallel3 = _interopRequireDefault(_parallel2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Run the `tasks` collection of functions in parallel, without waiting until
* the previous function has completed. If any of the functions pass an error to
* its callback, the main `callback` is immediately called with the value of the
* error. Once the `tasks` have completed, the results are passed to the final
* `callback` as an array.
*
* **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
* parallel execution of code. If your tasks do not use any timers or perform
* any I/O, they will actually be executed in series. Any synchronous setup
* sections for each task will happen one after the other. JavaScript remains
* single-threaded.
*
* **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
* execution of other tasks when a task fails.
*
* It is also possible to use an object instead of an array. Each property will
* be run as a function and the results will be passed to the final `callback`
* as an object instead of an array. This can be a more readable way of handling
* results from {@link async.parallel}.
*
* @name parallel
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
* [async functions]{@link AsyncFunction} to run.
* Each async function can complete with any number of optional `result` values.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed successfully. This function gets a results array
* (or object) containing all the result arguments passed to the task callbacks.
* Invoked with (err, results).
* @returns {Promise} a promise, if a callback is not passed
*
* @example
*
* //Using Callbacks
* async.parallel([
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ], function(err, results) {
* console.log(results);
* // results is equal to ['one','two'] even though
* // the second function had a shorter timeout.
* });
*
* // an example using an object instead of an array
* async.parallel({
* one: function(callback) {
* setTimeout(function() {
* callback(null, 1);
* }, 200);
* },
* two: function(callback) {
* setTimeout(function() {
* callback(null, 2);
* }, 100);
* }
* }, function(err, results) {
* console.log(results);
* // results is equal to: { one: 1, two: 2 }
* });
*
* //Using Promises
* async.parallel([
* 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'] even though
* // the second function had a shorter timeout.
* }).catch(err => {
* console.log(err);
* });
*
* // an example using an object instead of an array
* async.parallel({
* one: function(callback) {
* setTimeout(function() {
* callback(null, 1);
* }, 200);
* },
* two: function(callback) {
* setTimeout(function() {
* callback(null, 2);
* }, 100);
* }
* }).then(results => {
* console.log(results);
* // results is equal to: { one: 1, two: 2 }
* }).catch(err => {
* console.log(err);
* });
*
* //Using async/await
* async () => {
* try {
* let results = await async.parallel([
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ]);
* console.log(results);
* // results is equal to ['one','two'] even though
* // the second function had a shorter timeout.
* }
* catch (err) {
* console.log(err);
* }
* }
*
* // an example using an object instead of an array
* 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);
* }
* });
* console.log(results);
* // results is equal to: { one: 1, two: 2 }
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function parallel(tasks, callback) {
return (0, _parallel3.default)(_eachOf2.default, tasks, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parallelLimit;
var _eachOfLimit = require('./internal/eachOfLimit.js');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _parallel = require('./internal/parallel.js');
var _parallel2 = _interopRequireDefault(_parallel);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
* time.
*
* @name parallelLimit
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.parallel]{@link module:ControlFlow.parallel}
* @category Control Flow
* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
* [async functions]{@link AsyncFunction} to run.
* Each async function can complete with any number of optional `result` values.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed successfully. This function gets a results array
* (or object) containing all the result arguments passed to the task callbacks.
* Invoked with (err, results).
* @returns {Promise} a promise, if a callback is not passed
*/
function parallelLimit(tasks, limit, callback) {
return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (worker, concurrency) {
// Start with a normal queue
var q = (0, _queue2.default)(worker, concurrency);
var {
push,
pushAsync
} = q;
q._tasks = new _Heap2.default();
q._createTaskItem = ({ data, priority }, callback) => {
return {
data,
priority,
callback
};
};
function createDataItems(tasks, priority) {
if (!Array.isArray(tasks)) {
return { data: tasks, priority };
}
return tasks.map(data => {
return { data, priority };
});
}
// Override push to accept second parameter representing priority
q.push = function (data, priority = 0, callback) {
return push(createDataItems(data, priority), callback);
};
q.pushAsync = function (data, priority = 0, callback) {
return pushAsync(createDataItems(data, priority), callback);
};
// Remove unshift functions
delete q.unshift;
delete q.unshiftAsync;
return q;
};
var _queue = require('./queue.js');
var _queue2 = _interopRequireDefault(_queue);
var _Heap = require('./internal/Heap.js');
var _Heap2 = _interopRequireDefault(_Heap);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
/**
* The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
* completed in ascending priority order.
*
* @name priorityQueue
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.queue]{@link module:ControlFlow.queue}
* @category Control Flow
* @param {AsyncFunction} worker - An async function for processing a queued task.
* If you want to handle errors from an individual task, pass a callback to
* `q.push()`.
* Invoked with (task, callback).
* @param {number} concurrency - An `integer` for determining how many `worker`
* functions should be run in parallel. If omitted, the concurrency defaults to
* `1`. If the concurrency is `0`, an error is thrown.
* @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three
* differences between `queue` and `priorityQueue` objects:
* * `push(task, priority, [callback])` - `priority` should be a number. If an
* array of `tasks` is given, all tasks will be assigned the same priority.
* * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`,
* except this returns a promise that rejects if an error occurs.
* * The `unshift` and `unshiftAsync` methods were removed.
*/
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (worker, concurrency) {
var _worker = (0, _wrapAsync2.default)(worker);
return (0, _queue2.default)((items, cb) => {
_worker(items[0], cb);
}, concurrency, 1);
};
var _queue = require('./internal/queue.js');
var _queue2 = _interopRequireDefault(_queue);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
/**
* A queue of tasks for the worker function to complete.
* @typedef {Iterable} QueueObject
* @memberOf module:ControlFlow
* @property {Function} length - a function returning the number of items
* waiting to be processed. Invoke with `queue.length()`.
* @property {boolean} started - a boolean indicating whether or not any
* items have been pushed and processed by the queue.
* @property {Function} running - a function returning the number of items
* currently being processed. Invoke with `queue.running()`.
* @property {Function} workersList - a function returning the array of items
* currently being processed. Invoke with `queue.workersList()`.
* @property {Function} idle - a function returning false if there are items
* waiting or being processed, or true if not. Invoke with `queue.idle()`.
* @property {number} concurrency - an integer for determining how many `worker`
* functions should be run in parallel. This property can be changed after a
* `queue` is created to alter the concurrency on-the-fly.
* @property {number} payload - an integer that specifies how many items are
* passed to the worker function at a time. only applies if this is a
* [cargo]{@link module:ControlFlow.cargo} object
* @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
* once the `worker` has finished processing the task. Instead of a single task,
* a `tasks` array can be submitted. The respective callback is used for every
* task in the list. Invoke with `queue.push(task, [callback])`,
* @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
* Invoke with `queue.unshift(task, [callback])`.
* @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
* a promise that rejects if an error occurs.
* @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns
* a promise that rejects if an error occurs.
* @property {Function} remove - remove items from the queue that match a test
* function. The test function will be passed an object with a `data` property,
* and a `priority` property, if this is a
* [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
* Invoked with `queue.remove(testFn)`, where `testFn` is of the form
* `function ({data, priority}) {}` and returns a Boolean.
* @property {Function} saturated - a function that sets a callback that is
* called when the number of running workers hits the `concurrency` limit, and
* further tasks will be queued. If the callback is omitted, `q.saturated()`
* returns a promise for the next occurrence.
* @property {Function} unsaturated - a function that sets a callback that is
* called when the number of running workers is less than the `concurrency` &
* `buffer` limits, and further tasks will not be queued. If the callback is
* omitted, `q.unsaturated()` returns a promise for the next occurrence.
* @property {number} buffer - A minimum threshold buffer in order to say that
* the `queue` is `unsaturated`.
* @property {Function} empty - a function that sets a callback that is called
* when the last item from the `queue` is given to a `worker`. If the callback
* is omitted, `q.empty()` returns a promise for the next occurrence.
* @property {Function} drain - a function that sets a callback that is called
* when the last item from the `queue` has returned from the `worker`. If the
* callback is omitted, `q.drain()` returns a promise for the next occurrence.
* @property {Function} error - a function that sets a callback that is called
* when a task errors. Has the signature `function(error, task)`. If the
* callback is omitted, `error()` returns a promise that rejects on the next
* error.
* @property {boolean} paused - a boolean for determining whether the queue is
* in a paused state.
* @property {Function} pause - a function that pauses the processing of tasks
* until `resume()` is called. Invoke with `queue.pause()`.
* @property {Function} resume - a function that resumes the processing of
* queued tasks when the queue is paused. Invoke with `queue.resume()`.
* @property {Function} kill - a function that removes the `drain` callback and
* empties remaining tasks from the queue forcing it to go idle. No more tasks
* should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
*
* @example
* 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()
*/
/**
* Creates a `queue` object with the specified `concurrency`. Tasks added to the
* `queue` are processed in parallel (up to the `concurrency` limit). If all
* `worker`s are in progress, the task is queued until one becomes available.
* Once a `worker` completes a `task`, that `task`'s callback is called.
*
* @name queue
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @param {AsyncFunction} worker - An async function for processing a queued task.
* If you want to handle errors from an individual task, pass a callback to
* `q.push()`. Invoked with (task, callback).
* @param {number} [concurrency=1] - An `integer` for determining how many
* `worker` functions should be run in parallel. If omitted, the concurrency
* defaults to `1`. If the concurrency is `0`, an error is thrown.
* @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
* attached as certain properties to listen for specific events during the
* lifecycle of the queue.
* @example
*
* // create a queue object with concurrency 2
* var q = async.queue(function(task, callback) {
* console.log('hello ' + task.name);
* callback();
* }, 2);
*
* // assign a callback
* q.drain(function() {
* console.log('all items have been processed');
* });
* // or await the end
* await q.drain()
*
* // assign an error callback
* q.error(function(err, task) {
* console.error('task experienced an error');
* });
*
* // add some items to the queue
* q.push({name: 'foo'}, function(err) {
* console.log('finished processing foo');
* });
* // callback is optional
* q.push({name: 'bar'});
*
* // add some items to the queue (batch-wise)
* q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
* console.log('finished processing item');
* });
*
* // add some items to the front of the queue
* q.unshift({name: 'bar'}, function (err) {
* console.log('finished processing bar');
* });
*/
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _once = require('./internal/once.js');
var _once2 = _interopRequireDefault(_once);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Runs the `tasks` array of functions in parallel, without waiting until the
* previous function has completed. Once any of the `tasks` complete or pass an
* error to its callback, the main `callback` is immediately called. It's
* equivalent to `Promise.race()`.
*
* @name race
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
* to run. Each function can complete with an optional `result` value.
* @param {Function} callback - A callback to run once any of the functions have
* completed. This function gets an error or result from the first function that
* completed. Invoked with (err, result).
* @returns {Promise} a promise, if a callback is omitted
* @example
*
* async.race([
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ],
* // main callback
* function(err, result) {
* // the result will be equal to 'two' as it finishes earlier
* });
*/
function race(tasks, callback) {
callback = (0, _once2.default)(callback);
if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
if (!tasks.length) return callback();
for (var i = 0, l = tasks.length; i < l; i++) {
(0, _wrapAsync2.default)(tasks[i])(callback);
}
}
exports.default = (0, _awaitify2.default)(race, 2);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _eachOfSeries = require('./eachOfSeries.js');
var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
var _once = require('./internal/once.js');
var _once2 = _interopRequireDefault(_once);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Reduces `coll` into a single value using an async `iteratee` to return each
* successive step. `memo` is the initial state of the reduction. This function
* only operates in series.
*
* For performance reasons, it may make sense to split a call to this function
* into a parallel map, and then use the normal `Array.prototype.reduce` on the
* results. This function is for situations where each step in the reduction
* needs to be async; if you can get the data before reducing it, then it's
* probably a good idea to do so.
*
* @name reduce
* @static
* @memberOf module:Collections
* @method
* @alias inject
* @alias foldl
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {*} memo - The initial state of the reduction.
* @param {AsyncFunction} iteratee - A function applied to each item in the
* array to produce the next step in the reduction.
* The `iteratee` should complete with the next state of the reduction.
* If the iteratee completes with an error, the reduction is stopped and the
* main `callback` is immediately called with the error.
* Invoked with (memo, item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the reduced value. Invoked with
* (err, result).
* @returns {Promise} a promise, if no callback is passed
* @example
*
* // 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','file3.txt', 'file4.txt'];
*
* // asynchronous function that computes the file size in bytes
* // file size is added to the memoized value, then returned
* function getFileSizeInBytes(memo, file, callback) {
* fs.stat(file, function(err, stat) {
* if (err) {
* return callback(err);
* }
* callback(null, memo + stat.size);
* });
* }
*
* // Using callbacks
* async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
* if (err) {
* console.log(err);
* } else {
* console.log(result);
* // 6000
* // which is the sum of the file sizes of the three files
* }
* });
*
* // Error Handling
* async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
* if (err) {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* } else {
* console.log(result);
* }
* });
*
* // Using Promises
* async.reduce(fileList, 0, getFileSizeInBytes)
* .then( result => {
* console.log(result);
* // 6000
* // which is the sum of the file sizes of the three files
* }).catch( err => {
* console.log(err);
* });
*
* // Error Handling
* async.reduce(withMissingFileList, 0, getFileSizeInBytes)
* .then( result => {
* console.log(result);
* }).catch( err => {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* });
*
* // Using async/await
* async () => {
* try {
* let result = await async.reduce(fileList, 0, getFileSizeInBytes);
* console.log(result);
* // 6000
* // which is the sum of the file sizes of the three files
* }
* catch (err) {
* console.log(err);
* }
* }
*
* // Error Handling
* async () => {
* try {
* let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
* console.log(result);
* }
* catch (err) {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* }
* }
*
*/
function reduce(coll, memo, iteratee, callback) {
callback = (0, _once2.default)(callback);
var _iteratee = (0, _wrapAsync2.default)(iteratee);
return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => {
_iteratee(memo, x, (err, v) => {
memo = v;
iterCb(err);
});
}, err => callback(err, memo));
}
exports.default = (0, _awaitify2.default)(reduce, 4);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reduceRight;
var _reduce = require('./reduce.js');
var _reduce2 = _interopRequireDefault(_reduce);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
*
* @name reduceRight
* @static
* @memberOf module:Collections
* @method
* @see [async.reduce]{@link module:Collections.reduce}
* @alias foldr
* @category Collection
* @param {Array} array - A collection to iterate over.
* @param {*} memo - The initial state of the reduction.
* @param {AsyncFunction} iteratee - A function applied to each item in the
* array to produce the next step in the reduction.
* The `iteratee` should complete with the next state of the reduction.
* If the iteratee completes with an error, the reduction is stopped and the
* main `callback` is immediately called with the error.
* Invoked with (memo, item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the reduced value. Invoked with
* (err, result).
* @returns {Promise} a promise, if no callback is passed
*/
function reduceRight(array, memo, iteratee, callback) {
var reversed = [...array].reverse();
return (0, _reduce2.default)(reversed, memo, iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reflect;
var _initialParams = require('./internal/initialParams.js');
var _initialParams2 = _interopRequireDefault(_initialParams);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Wraps the async function in another function that always completes with a
* result object, even when it errors.
*
* The result object has either the property `error` or `value`.
*
* @name reflect
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {AsyncFunction} fn - The async function you want to wrap
* @returns {Function} - A function that always passes null to it's callback as
* the error. The second argument to the callback will be an `object` with
* either an `error` or a `value` property.
* @example
*
* async.parallel([
* async.reflect(function(callback) {
* // do some stuff ...
* callback(null, 'one');
* }),
* async.reflect(function(callback) {
* // do some more stuff but error ...
* callback('bad stuff happened');
* }),
* async.reflect(function(callback) {
* // do some more stuff ...
* callback(null, 'two');
* })
* ],
* // optional callback
* function(err, results) {
* // values
* // results[0].value = 'one'
* // results[1].error = 'bad stuff happened'
* // results[2].value = 'two'
* });
*/
function reflect(fn) {
var _fn = (0, _wrapAsync2.default)(fn);
return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) {
args.push((error, ...cbArgs) => {
let retVal = {};
if (error) {
retVal.error = error;
}
if (cbArgs.length > 0) {
var value = cbArgs;
if (cbArgs.length <= 1) {
[value] = cbArgs;
}
retVal.value = value;
}
reflectCallback(null, retVal);
});
return _fn.apply(this, args);
});
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = reflectAll;
var _reflect = require('./reflect.js');
var _reflect2 = _interopRequireDefault(_reflect);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A helper function that wraps an array or an object of functions with `reflect`.
*
* @name reflectAll
* @static
* @memberOf module:Utils
* @method
* @see [async.reflect]{@link module:Utils.reflect}
* @category Util
* @param {Array|Object|Iterable} tasks - The collection of
* [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
* @returns {Array} Returns an array of async functions, each wrapped in
* `async.reflect`
* @example
*
* let tasks = [
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* // do some more stuff but error ...
* callback(new Error('bad stuff happened'));
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ];
*
* async.parallel(async.reflectAll(tasks),
* // optional callback
* function(err, results) {
* // values
* // results[0].value = 'one'
* // results[1].error = Error('bad stuff happened')
* // results[2].value = 'two'
* });
*
* // an example using an object instead of an array
* let tasks = {
* one: function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* two: function(callback) {
* callback('two');
* },
* three: function(callback) {
* setTimeout(function() {
* callback(null, 'three');
* }, 100);
* }
* };
*
* async.parallel(async.reflectAll(tasks),
* // optional callback
* function(err, results) {
* // values
* // results.one.value = 'one'
* // results.two.error = 'two'
* // results.three.value = 'three'
* });
*/
function reflectAll(tasks) {
var results;
if (Array.isArray(tasks)) {
results = tasks.map(_reflect2.default);
} else {
results = {};
Object.keys(tasks).forEach(key => {
results[key] = _reflect2.default.call(this, tasks[key]);
});
}
return results;
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reject2 = require('./internal/reject.js');
var _reject3 = _interopRequireDefault(_reject2);
var _eachOf = require('./eachOf.js');
var _eachOf2 = _interopRequireDefault(_eachOf);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
*
* @name reject
* @static
* @memberOf module:Collections
* @method
* @see [async.filter]{@link module:Collections.filter}
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {Function} iteratee - An async truth test to apply to each item in
* `coll`.
* The should complete with a boolean value as its `result`.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @returns {Promise} a promise, if no callback is passed
* @example
*
* // dir1 is a directory that contains file1.txt, file2.txt
* // dir2 is a directory that contains file3.txt, file4.txt
* // dir3 is a directory that contains file5.txt
*
* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
*
* // asynchronous function that checks if a file exists
* function fileExists(file, callback) {
* fs.access(file, fs.constants.F_OK, (err) => {
* callback(null, !err);
* });
* }
*
* // Using callbacks
* async.reject(fileList, fileExists, function(err, results) {
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* });
*
* // Using Promises
* async.reject(fileList, fileExists)
* .then( results => {
* console.log(results);
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* }).catch( err => {
* console.log(err);
* });
*
* // Using async/await
* async () => {
* try {
* let results = await async.reject(fileList, fileExists);
* console.log(results);
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function reject(coll, iteratee, callback) {
return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(reject, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reject2 = require('./internal/reject.js');
var _reject3 = _interopRequireDefault(_reject2);
var _eachOfLimit = require('./internal/eachOfLimit.js');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
* time.
*
* @name rejectLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.reject]{@link module:Collections.reject}
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - An async truth test to apply to each item in
* `coll`.
* The should complete with a boolean value as its `result`.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @returns {Promise} a promise, if no callback is passed
*/
function rejectLimit(coll, limit, iteratee, callback) {
return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(rejectLimit, 4);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reject2 = require('./internal/reject.js');
var _reject3 = _interopRequireDefault(_reject2);
var _eachOfSeries = require('./eachOfSeries.js');
var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
*
* @name rejectSeries
* @static
* @memberOf module:Collections
* @method
* @see [async.reject]{@link module:Collections.reject}
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {Function} iteratee - An async truth test to apply to each item in
* `coll`.
* The should complete with a boolean value as its `result`.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @returns {Promise} a promise, if no callback is passed
*/
function rejectSeries(coll, iteratee, callback) {
return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(rejectSeries, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = retry;
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
var _promiseCallback = require('./internal/promiseCallback.js');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function constant(value) {
return function () {
return value;
};
}
/**
* 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.
*
* @name retry
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @see [async.retryable]{@link module:ControlFlow.retryable}
* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
* object with `times` and `interval` or a number.
* * `times` - The number of attempts to make before giving up. The default
* is `5`.
* * `interval` - The time to wait between retries, in milliseconds. The
* default is `0`. The interval may also be specified as a function of the
* retry count (see example).
* * `errorFilter` - 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 with the current
* attempt's error and result being returned to the final callback.
* Invoked with (err).
* * If `opts` is a number, the number specifies the number of times to retry,
* with the default interval of `0`.
* @param {AsyncFunction} task - An async function to retry.
* Invoked with (callback).
* @param {Function} [callback] - An optional callback which is called when the
* task has succeeded, or after the final failed attempt. It receives the `err`
* and `result` arguments of the last attempt at completing the `task`. Invoked
* with (err, results).
* @returns {Promise} a promise if no callback provided
*
* @example
*
* // The `retry` function can be used as a stand-alone control flow by passing
* // a callback, as shown below:
*
* // 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
* // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
* 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 the default 5 times no delay between each retry
* async.retry(apiMethod, function(err, result) {
* // do something with the result
* });
*
* // try calling apiMethod only when error condition satisfies, all other
* // errors will abort the retry control flow and return to final callback
* 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
* });
*
* // to retry individual methods that are not as reliable within other
* // control flow functions, use the `retryable` wrapper:
* async.auto({
* users: api.getUsers.bind(api),
* payments: async.retryable(3, api.getPayments.bind(api))
* }, function(err, results) {
* // do something with the results
* });
*
*/
const DEFAULT_TIMES = 5;
const DEFAULT_INTERVAL = 0;
function retry(opts, task, callback) {
var options = {
times: DEFAULT_TIMES,
intervalFunc: constant(DEFAULT_INTERVAL)
};
if (arguments.length < 3 && typeof opts === 'function') {
callback = task || (0, _promiseCallback.promiseCallback)();
task = opts;
} else {
parseTimes(options, opts);
callback = callback || (0, _promiseCallback.promiseCallback)();
}
if (typeof task !== 'function') {
throw new Error("Invalid arguments for async.retry");
}
var _task = (0, _wrapAsync2.default)(task);
var attempt = 1;
function retryAttempt() {
_task((err, ...args) => {
if (err === false) return;
if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) {
setTimeout(retryAttempt, options.intervalFunc(attempt - 1));
} else {
callback(err, ...args);
}
});
}
retryAttempt();
return callback[_promiseCallback.PROMISE_SYMBOL];
}
function parseTimes(acc, t) {
if (typeof t === 'object') {
acc.times = +t.times || DEFAULT_TIMES;
acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL);
acc.errorFilter = t.errorFilter;
} else if (typeof t === 'number' || typeof t === 'string') {
acc.times = +t || DEFAULT_TIMES;
} else {
throw new Error("Invalid arguments for async.retry");
}
}
module.exports = exports['default'];
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment