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
});
exports.default = retryable;
var _retry = require('./retry.js');
var _retry2 = _interopRequireDefault(_retry);
var _initialParams = require('./internal/initialParams.js');
var _initialParams2 = _interopRequireDefault(_initialParams);
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 }; }
/**
* A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
* wraps a task and makes it retryable, rather than immediately calling it
* with retries.
*
* @name retryable
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.retry]{@link module:ControlFlow.retry}
* @category Control Flow
* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
* options, exactly the same as from `retry`, except for a `opts.arity` that
* is the arity of the `task` function, defaulting to `task.length`
* @param {AsyncFunction} task - the asynchronous function to wrap.
* This function will be passed any arguments passed to the returned wrapper.
* Invoked with (...args, callback).
* @returns {AsyncFunction} The wrapped function, which when invoked, will
* retry on an error, based on the parameters specified in `opts`.
* This function will accept the same parameters as `task`.
* @example
*
* async.auto({
* dep1: async.retryable(3, getFromFlakyService),
* process: ["dep1", async.retryable(3, function (results, cb) {
* maybeProcessData(results.dep1, cb);
* })]
* }, callback);
*/
function retryable(opts, task) {
if (!task) {
task = opts;
opts = null;
}
let arity = opts && opts.arity || task.length;
if ((0, _wrapAsync.isAsync)(task)) {
arity += 1;
}
var _task = (0, _wrapAsync2.default)(task);
return (0, _initialParams2.default)((args, callback) => {
if (args.length < arity - 1 || callback == null) {
args.push(callback);
callback = (0, _promiseCallback.promiseCallback)();
}
function taskFn(cb) {
_task(...args, cb);
}
if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback);
return callback[_promiseCallback.PROMISE_SYMBOL];
});
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _filter2 = require('./internal/filter.js');
var _filter3 = _interopRequireDefault(_filter2);
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 }; }
/**
* Returns a new array of all the values in `coll` which pass an async truth
* test. This operation is performed in parallel, but the results array will be
* in the same order as the original.
*
* @name filter
* @static
* @memberOf module:Collections
* @method
* @alias select
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. 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 provided
* @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 files = ['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.filter(files, fileExists, function(err, results) {
* if(err) {
* console.log(err);
* } else {
* console.log(results);
* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
* // results is now an array of the existing files
* }
* });
*
* // Using Promises
* async.filter(files, fileExists)
* .then(results => {
* console.log(results);
* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
* // results is now an array of the existing files
* }).catch(err => {
* console.log(err);
* });
*
* // Using async/await
* async () => {
* try {
* let results = await async.filter(files, fileExists);
* console.log(results);
* // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
* // results is now an array of the existing files
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function filter(coll, iteratee, callback) {
return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(filter, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _filter2 = require('./internal/filter.js');
var _filter3 = _interopRequireDefault(_filter2);
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 [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
* time.
*
* @name filterLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.filter]{@link module:Collections.filter}
* @alias selectLimit
* @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 - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. 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 provided
*/
function filterLimit(coll, limit, iteratee, callback) {
return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(filterLimit, 4);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _filter2 = require('./internal/filter.js');
var _filter3 = _interopRequireDefault(_filter2);
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 [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
*
* @name filterSeries
* @static
* @memberOf module:Collections
* @method
* @see [async.filter]{@link module:Collections.filter}
* @alias selectSeries
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. 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 provided
*/
function filterSeries(coll, iteratee, callback) {
return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(filterSeries, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = seq;
var _reduce = require('./reduce.js');
var _reduce2 = _interopRequireDefault(_reduce);
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 }; }
/**
* Version of the compose function that is more natural to read. Each function
* consumes the return value of the previous function. It is the equivalent of
* [compose]{@link module:ControlFlow.compose} with the arguments reversed.
*
* Each function is executed with the `this` binding of the composed function.
*
* @name seq
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.compose]{@link module:ControlFlow.compose}
* @category Control Flow
* @param {...AsyncFunction} functions - the asynchronous functions to compose
* @returns {Function} a function that composes the `functions` in order
* @example
*
* // Requires lodash (or underscore), express3 and dresende's orm2.
* // Part of an app, that fetches cats of the logged user.
* // This example uses `seq` function to avoid overnesting and error
* // handling clutter.
* app.get('/cats', function(request, response) {
* var User = request.models.User;
* async.seq(
* User.get.bind(User), // 'User.get' has signature (id, callback(err, data))
* function(user, fn) {
* user.getCats(fn); // 'getCats' has signature (callback(err, data))
* }
* )(req.session.user_id, function (err, cats) {
* if (err) {
* console.error(err);
* response.json({ status: 'error', message: err.message });
* } else {
* response.json({ status: 'ok', message: 'Cats found', data: cats });
* }
* });
* });
*/
function seq(...functions) {
var _functions = functions.map(_wrapAsync2.default);
return function (...args) {
var that = this;
var cb = args[args.length - 1];
if (typeof cb == 'function') {
args.pop();
} else {
cb = (0, _promiseCallback.promiseCallback)();
}
(0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => {
fn.apply(that, newargs.concat((err, ...nextargs) => {
iterCb(err, nextargs);
}));
}, (err, results) => cb(err, ...results));
return cb[_promiseCallback.PROMISE_SYMBOL];
};
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = series;
var _parallel2 = require('./internal/parallel.js');
var _parallel3 = _interopRequireDefault(_parallel2);
var _eachOfSeries = require('./eachOfSeries.js');
var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Run the functions in the `tasks` collection in series, each one running once
* the previous function has completed. If any functions in the series pass an
* error to its callback, no more functions are run, and `callback` is
* immediately called with the value of the error. Otherwise, `callback`
* receives an array of results when `tasks` have completed.
*
* 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.series}.
*
* **Note** that while many implementations preserve the order of object
* properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
* explicitly states that
*
* > The mechanics and order of enumerating the properties is not specified.
*
* So if you rely on the order in which your series of functions are executed,
* and want this to work on all platforms, consider using an array.
*
* @name series
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
* [async functions]{@link AsyncFunction} to run in series.
* Each function can complete with any number of optional `result` values.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed. This function gets a results array (or object)
* containing all the result arguments passed to the `task` callbacks. Invoked
* with (err, result).
* @return {Promise} a promise, if no callback is passed
* @example
*
* //Using Callbacks
* 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 }
* });
*
* //Using Promises
* 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 array
* 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);
* }
* }).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.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);
* }
* ]);
* console.log(results);
* // results is equal to ['one','two']
* }
* 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() {
* // do some async task
* callback(null, 1);
* }, 200);
* },
* two: function(callback) {
* setTimeout(function() {
* // then do another async task
* callback(null, 2);
* }, 100);
* }
* });
* console.log(results);
* // results is equal to: { one: 1, two: 2 }
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function series(tasks, callback) {
return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _setImmediate = require('./internal/setImmediate.js');
var _setImmediate2 = _interopRequireDefault(_setImmediate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Calls `callback` on a later loop around the event loop. In Node.js this just
* calls `setImmediate`. 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 setImmediate
* @static
* @memberOf module:Utils
* @method
* @see [async.nextTick]{@link module:Utils.nextTick}
* @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);
*/
exports.default = _setImmediate2.default;
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createTester = require('./internal/createTester.js');
var _createTester2 = _interopRequireDefault(_createTester);
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 }; }
/**
* Returns `true` if at least one element in the `coll` satisfies an async test.
* If any iteratee call returns `true`, the main `callback` is immediately
* called.
*
* @name some
* @static
* @memberOf module:Collections
* @method
* @alias any
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {AsyncFunction} iteratee - An async truth test to apply to each item
* in the collections in parallel.
* The iteratee should complete with a boolean `result` value.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
* @returns {Promise} a promise, if no callback provided
* @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
* // dir4 does not exist
*
* // 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.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
* function(err, result) {
* console.log(result);
* // true
* // result is true since some file in the list exists
* }
*);
*
* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
* function(err, result) {
* console.log(result);
* // false
* // result is false since none of the files exists
* }
*);
*
* // Using Promises
* async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
* .then( result => {
* console.log(result);
* // true
* // result is true since some file in the list exists
* }).catch( err => {
* console.log(err);
* });
*
* async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
* .then( result => {
* console.log(result);
* // false
* // result is false since none of the files exists
* }).catch( err => {
* console.log(err);
* });
*
* // Using async/await
* async () => {
* try {
* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
* console.log(result);
* // true
* // result is true since some file in the list exists
* }
* catch (err) {
* console.log(err);
* }
* }
*
* async () => {
* try {
* let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
* console.log(result);
* // false
* // result is false since none of the files exists
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function some(coll, iteratee, callback) {
return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(some, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createTester = require('./internal/createTester.js');
var _createTester2 = _interopRequireDefault(_createTester);
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 [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
*
* @name someLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.some]{@link module:Collections.some}
* @alias anyLimit
* @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 {AsyncFunction} iteratee - An async truth test to apply to each item
* in the collections in parallel.
* The iteratee should complete with a boolean `result` value.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
* @returns {Promise} a promise, if no callback provided
*/
function someLimit(coll, limit, iteratee, callback) {
return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(someLimit, 4);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createTester = require('./internal/createTester.js');
var _createTester2 = _interopRequireDefault(_createTester);
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 [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
*
* @name someSeries
* @static
* @memberOf module:Collections
* @method
* @see [async.some]{@link module:Collections.some}
* @alias anySeries
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {AsyncFunction} iteratee - An async truth test to apply to each item
* in the collections in series.
* The iteratee should complete with a boolean `result` value.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
* @returns {Promise} a promise, if no callback provided
*/
function someSeries(coll, iteratee, callback) {
return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(someSeries, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _map = require('./map.js');
var _map2 = _interopRequireDefault(_map);
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 }; }
/**
* Sorts a list by the results of running each `coll` value through an async
* `iteratee`.
*
* @name sortBy
* @static
* @memberOf module:Collections
* @method
* @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 a value to use as the sort criteria as
* its `result`.
* Invoked with (item, callback).
* @param {Function} callback - A callback which is called after all the
* `iteratee` functions have finished, or an error occurs. Results is the items
* from the original `coll` sorted by the values returned by the `iteratee`
* calls. Invoked with (err, results).
* @returns {Promise} a promise, if no callback passed
* @example
*
* // 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);
* }
* }
* );
*
* // Using Promises
* async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)
* .then( results => {
* 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']
* }).catch( err => {
* console.log(err);
* });
*
* // Error handling
* async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], 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.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
* 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']
* }
* catch (err) {
* console.log(err);
* }
* })();
*
* // Error handling
* async () => {
* try {
* let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
* console.log(results);
* }
* catch (err) {
* console.log(err);
* // [ Error: ENOENT: no such file or directory ]
* }
* }
*
*/
function sortBy(coll, iteratee, callback) {
var _iteratee = (0, _wrapAsync2.default)(iteratee);
return (0, _map2.default)(coll, (x, iterCb) => {
_iteratee(x, (err, criteria) => {
if (err) return iterCb(err);
iterCb(err, { value: x, criteria });
});
}, (err, results) => {
if (err) return callback(err);
callback(null, results.sort(comparator).map(v => v.value));
});
function comparator(left, right) {
var a = left.criteria,
b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
}
exports.default = (0, _awaitify2.default)(sortBy, 3);
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = timeout;
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 }; }
/**
* Sets a time limit on an asynchronous function. If the function does not call
* its callback within the specified milliseconds, it will be called with a
* timeout error. The code property for the error object will be `'ETIMEDOUT'`.
*
* @name timeout
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {AsyncFunction} asyncFn - The async function to limit in time.
* @param {number} milliseconds - The specified time limit.
* @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
* to timeout Error for more information..
* @returns {AsyncFunction} Returns a wrapped function that can be used with any
* of the control flow functions.
* Invoke this function with the same parameters as you would `asyncFunc`.
* @example
*
* function myFunction(foo, callback) {
* doAsyncTask(foo, function(err, data) {
* // handle errors
* if (err) return callback(err);
*
* // do some stuff ...
*
* // return processed data
* return callback(null, data);
* });
* }
*
* var wrapped = async.timeout(myFunction, 1000);
*
* // call `wrapped` as you would `myFunction`
* wrapped({ bar: 'bar' }, function(err, data) {
* // if `myFunction` takes < 1000 ms to execute, `err`
* // and `data` will have their expected values
*
* // else `err` will be an Error with the code 'ETIMEDOUT'
* });
*/
function timeout(asyncFn, milliseconds, info) {
var fn = (0, _wrapAsync2.default)(asyncFn);
return (0, _initialParams2.default)((args, callback) => {
var timedOut = false;
var timer;
function timeoutCallback() {
var name = asyncFn.name || 'anonymous';
var error = new Error('Callback function "' + name + '" timed out.');
error.code = 'ETIMEDOUT';
if (info) {
error.info = info;
}
timedOut = true;
callback(error);
}
args.push((...cbArgs) => {
if (!timedOut) {
callback(...cbArgs);
clearTimeout(timer);
}
});
// setup timer and call original function
timer = setTimeout(timeoutCallback, milliseconds);
fn(...args);
});
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = times;
var _timesLimit = require('./timesLimit.js');
var _timesLimit2 = _interopRequireDefault(_timesLimit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Calls the `iteratee` function `n` times, and accumulates results in the same
* manner you would use with [map]{@link module:Collections.map}.
*
* @name times
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.map]{@link module:Collections.map}
* @category Control Flow
* @param {number} n - The number of times to run the function.
* @param {AsyncFunction} iteratee - The async function to call `n` times.
* Invoked with the iteration index and a callback: (n, next).
* @param {Function} callback - see {@link module:Collections.map}.
* @returns {Promise} a promise, if no callback is provided
* @example
*
* // Pretend this is some complicated async factory
* var createUser = function(id, callback) {
* callback(null, {
* id: 'user' + id
* });
* };
*
* // generate 5 users
* async.times(5, function(n, next) {
* createUser(n, function(err, user) {
* next(err, user);
* });
* }, function(err, users) {
* // we should now have 5 users
* });
*/
function times(n, iteratee, callback) {
return (0, _timesLimit2.default)(n, Infinity, iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = timesLimit;
var _mapLimit = require('./mapLimit.js');
var _mapLimit2 = _interopRequireDefault(_mapLimit);
var _range = require('./internal/range.js');
var _range2 = _interopRequireDefault(_range);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
* time.
*
* @name timesLimit
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.times]{@link module:ControlFlow.times}
* @category Control Flow
* @param {number} count - The number of times to run the function.
* @param {number} limit - The maximum number of async operations at a time.
* @param {AsyncFunction} iteratee - The async function to call `n` times.
* Invoked with the iteration index and a callback: (n, next).
* @param {Function} callback - see [async.map]{@link module:Collections.map}.
* @returns {Promise} a promise, if no callback is provided
*/
function timesLimit(count, limit, iteratee, callback) {
var _iteratee = (0, _wrapAsync2.default)(iteratee);
return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = timesSeries;
var _timesLimit = require('./timesLimit.js');
var _timesLimit2 = _interopRequireDefault(_timesLimit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
*
* @name timesSeries
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.times]{@link module:ControlFlow.times}
* @category Control Flow
* @param {number} n - The number of times to run the function.
* @param {AsyncFunction} iteratee - The async function to call `n` times.
* Invoked with the iteration index and a callback: (n, next).
* @param {Function} callback - see {@link module:Collections.map}.
* @returns {Promise} a promise, if no callback is provided
*/
function timesSeries(n, iteratee, callback) {
return (0, _timesLimit2.default)(n, 1, iteratee, callback);
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transform;
var _eachOf = require('./eachOf.js');
var _eachOf2 = _interopRequireDefault(_eachOf);
var _once = require('./internal/once.js');
var _once2 = _interopRequireDefault(_once);
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 }; }
/**
* A relative of `reduce`. Takes an Object or Array, and iterates over each
* element in parallel, each step potentially mutating an `accumulator` value.
* The type of the accumulator defaults to the type of collection passed in.
*
* @name transform
* @static
* @memberOf module:Collections
* @method
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {*} [accumulator] - The initial state of the transform. If omitted,
* it will default to an empty Object or Array, depending on the type of `coll`
* @param {AsyncFunction} iteratee - A function applied to each item in the
* collection that potentially modifies the accumulator.
* Invoked with (accumulator, item, key, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the transformed accumulator.
* Invoked with (err, result).
* @returns {Promise} a promise, if no callback provided
* @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
*
* // helper function that returns human-readable size format from bytes
* function formatBytes(bytes, decimals = 2) {
* // implementation not included for brevity
* return humanReadbleFilesize;
* }
*
* const fileList = ['file1.txt','file2.txt','file3.txt'];
*
* // asynchronous function that returns the file size, transformed to human-readable format
* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
* function transformFileSize(acc, value, key, callback) {
* fs.stat(value, function(err, stat) {
* if (err) {
* return callback(err);
* }
* acc[key] = formatBytes(stat.size);
* callback(null);
* });
* }
*
* // Using callbacks
* async.transform(fileList, transformFileSize, function(err, result) {
* if(err) {
* console.log(err);
* } else {
* console.log(result);
* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
* }
* });
*
* // Using Promises
* async.transform(fileList, transformFileSize)
* .then(result => {
* console.log(result);
* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
* }).catch(err => {
* console.log(err);
* });
*
* // Using async/await
* (async () => {
* try {
* let result = await async.transform(fileList, transformFileSize);
* console.log(result);
* // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
* }
* catch (err) {
* console.log(err);
* }
* })();
*
* @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
*
* // helper function that returns human-readable size format from bytes
* function formatBytes(bytes, decimals = 2) {
* // implementation not included for brevity
* return humanReadbleFilesize;
* }
*
* const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };
*
* // asynchronous function that returns the file size, transformed to human-readable format
* // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
* function transformFileSize(acc, value, key, callback) {
* fs.stat(value, function(err, stat) {
* if (err) {
* return callback(err);
* }
* acc[key] = formatBytes(stat.size);
* callback(null);
* });
* }
*
* // Using callbacks
* async.transform(fileMap, transformFileSize, function(err, result) {
* if(err) {
* console.log(err);
* } else {
* console.log(result);
* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
* }
* });
*
* // Using Promises
* async.transform(fileMap, transformFileSize)
* .then(result => {
* console.log(result);
* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
* }).catch(err => {
* console.log(err);
* });
*
* // Using async/await
* async () => {
* try {
* let result = await async.transform(fileMap, transformFileSize);
* console.log(result);
* // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function transform(coll, accumulator, iteratee, callback) {
if (arguments.length <= 3 && typeof accumulator === 'function') {
callback = iteratee;
iteratee = accumulator;
accumulator = Array.isArray(coll) ? [] : {};
}
callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)());
var _iteratee = (0, _wrapAsync2.default)(iteratee);
(0, _eachOf2.default)(coll, (v, k, cb) => {
_iteratee(accumulator, v, k, cb);
}, err => callback(err, accumulator));
return callback[_promiseCallback.PROMISE_SYMBOL];
}
module.exports = exports['default'];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _eachSeries = require('./eachSeries.js');
var _eachSeries2 = _interopRequireDefault(_eachSeries);
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 }; }
/**
* 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|AsyncIterable|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).
* @returns {Promise} a promise, if no callback is passed
* @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.
* });
*
*/
function tryEach(tasks, callback) {
var error = null;
var result;
return (0, _eachSeries2.default)(tasks, (task, taskCb) => {
(0, _wrapAsync2.default)(task)((err, ...args) => {
if (err === false) return taskCb(err);
if (args.length < 2) {
[result] = args;
} else {
result = args;
}
error = err;
taskCb(err ? null : {});
});
}, () => callback(error, result));
}
exports.default = (0, _awaitify2.default)(tryEach);
module.exports = exports['default'];
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unmemoize;
/**
* Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
* unmemoized form. Handy for testing.
*
* @name unmemoize
* @static
* @memberOf module:Utils
* @method
* @see [async.memoize]{@link module:Utils.memoize}
* @category Util
* @param {AsyncFunction} fn - the memoized function
* @returns {AsyncFunction} a function that calls the original unmemoized function
*/
function unmemoize(fn) {
return (...args) => {
return (fn.unmemoized || fn)(...args);
};
}
module.exports = exports["default"];
\ No newline at end of file
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = until;
var _whilst = require('./whilst.js');
var _whilst2 = _interopRequireDefault(_whilst);
var _wrapAsync = require('./internal/wrapAsync.js');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
* stopped, or an error occurs. `callback` will be passed an error and any
* arguments passed to the final `iteratee`'s callback.
*
* The inverse of [whilst]{@link module:ControlFlow.whilst}.
*
* @name until
* @static
* @memberOf module:ControlFlow
* @method
* @see [async.whilst]{@link module:ControlFlow.whilst}
* @category Control Flow
* @param {AsyncFunction} test - asynchronous truth test to perform before each
* execution of `iteratee`. Invoked with (callback).
* @param {AsyncFunction} iteratee - An async function which is called each time
* `test` fails. Invoked with (callback).
* @param {Function} [callback] - A callback which is called after the test
* function has passed and repeated execution of `iteratee` has stopped. `callback`
* will be passed an error and any arguments passed to the final `iteratee`'s
* callback. Invoked with (err, [results]);
* @returns {Promise} a promise, if a callback is not passed
*
* @example
* const results = []
* let finished = false
* async.until(function test(cb) {
* cb(null, finished)
* }, function iter(next) {
* fetchPage(url, (err, body) => {
* if (err) return next(err)
* results = results.concat(body.objects)
* finished = !!body.next
* next(err)
* })
* }, function done (err) {
* // all pages have been fetched
* })
*/
function until(test, iteratee, callback) {
const _test = (0, _wrapAsync2.default)(test);
return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback);
}
module.exports = exports['default'];
\ 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 _onlyOnce = require('./internal/onlyOnce.js');
var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
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 series, each passing their results to
* the next in the array. However, if any of the `tasks` pass an error to their
* own callback, the next function is not executed, and the main `callback` is
* immediately called with the error.
*
* @name waterfall
* @static
* @memberOf module:ControlFlow
* @method
* @category Control Flow
* @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
* to run.
* Each function should complete with any number of `result` values.
* The `result` values will be passed as arguments, in order, to the next task.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed. This will be passed the results of the last task's
* callback. Invoked with (err, [results]).
* @returns {Promise} a promise, if a callback is omitted
* @example
*
* async.waterfall([
* function(callback) {
* callback(null, 'one', 'two');
* },
* function(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* },
* function(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
* ], function (err, result) {
* // result now equals 'done'
* });
*
* // Or, with named functions:
* async.waterfall([
* myFirstFunction,
* mySecondFunction,
* myLastFunction,
* ], function (err, result) {
* // result now equals 'done'
* });
* function myFirstFunction(callback) {
* callback(null, 'one', 'two');
* }
* function mySecondFunction(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* }
* function myLastFunction(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
*/
function waterfall(tasks, callback) {
callback = (0, _once2.default)(callback);
if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
if (!tasks.length) return callback();
var taskIndex = 0;
function nextTask(args) {
var task = (0, _wrapAsync2.default)(tasks[taskIndex++]);
task(...args, (0, _onlyOnce2.default)(next));
}
function next(err, ...args) {
if (err === false) return;
if (err || taskIndex === tasks.length) {
return callback(err, ...args);
}
nextTask(args);
}
nextTask([]);
}
exports.default = (0, _awaitify2.default)(waterfall);
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