code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
; _proto.parseGroupOfType = function parseGroupOfType(name, type, optional) { switch (type) { case "color": return this.parseColorGroup(optional); case "size": return this.parseSizeGroup(optional); case "url": return this.parseUrlGroup(optional); case "math": case "text": return this.parseArgumentGroup(optional, type); case "hbox": { // hbox argument type wraps the argument in the equivalent of // \hbox, which is like \text but switching to \textstyle size. var group = this.parseArgumentGroup(optional, "text"); return group != null ? { type: "styling", mode: group.mode, body: [group], style: "text" // simulate \textstyle } : null; } case "raw": { var token = this.parseStringGroup("raw", optional); return token != null ? { type: "raw", mode: "text", string: token.text } : null; } case "primitive": { if (optional) { throw new src_ParseError("A primitive argument cannot be optional"); } var _group = this.parseGroup(name); if (_group == null) { throw new src_ParseError("Expected group as " + name, this.fetch()); } return _group; } case "original": case null: case undefined: return this.parseArgumentGroup(optional); default: throw new src_ParseError("Unknown group type as " + name, this.fetch());
Parses a group when the mode is changing.
parseGroupOfType ( name , type , optional )
javascript
colinwilson/lotusdocs
assets/docs/js/katex.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js
MIT
; _proto.consumeSpaces = function consumeSpaces() { while (this.fetch().text === " ") { this.consume();
Discard any space tokens, fetching the next non-space token.
consumeSpaces ( )
javascript
colinwilson/lotusdocs
assets/docs/js/katex.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js
MIT
; _proto.parseStringGroup = function parseStringGroup(modeName, // Used to describe the mode in error messages. optional) { var argToken = this.gullet.scanArgument(optional); if (argToken == null) { return null; } var str = ""; var nextToken; while ((nextToken = this.fetch()).text !== "EOF") { str += nextToken.text; this.consume(); } this.consume(); // consume the end of the argument argToken.text = str;
Parses a group, essentially returning the string formed by the brace-enclosed tokens plus some position information.
parseStringGroup ( modeName , optional )
javascript
colinwilson/lotusdocs
assets/docs/js/katex.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js
MIT
; _proto.parseRegexGroup = function parseRegexGroup(regex, modeName // Used to describe the mode in error messages. ) { var firstToken = this.fetch(); var lastToken = firstToken; var str = ""; var nextToken; while ((nextToken = this.fetch()).text !== "EOF" && regex.test(str + nextToken.text)) { lastToken = nextToken; str += lastToken.text; this.consume(); } if (str === "") { throw new src_ParseError("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken); }
Parses a regex-delimited group: the largest sequence of tokens whose concatenated strings match `regex`. Returns the string formed by the tokens plus some position information.
parseRegexGroup ( regex , modeName )
javascript
colinwilson/lotusdocs
assets/docs/js/katex.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/katex.js
MIT
/******/ !function() { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function() { return module['default']; } : /******/ function() { return module; }; /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ }();
****/ } ****/ **********************************************************************/ ****/ /* webpack/runtime/compat get default export */
(anonymous) ( )
javascript
colinwilson/lotusdocs
assets/docs/js/auto-render.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/auto-render.js
MIT
type: function (o) { return Object.prototype.toString.call(o).slice(8, -1); },
Returns the name of the type of the given value. @param {any} o @returns {string} @example type(null) === 'Null' type(undefined) === 'Undefined' type(123) === 'Number' type('foo') === 'String' type(true) === 'Boolean' type([1, 2]) === 'Array' type({}) === 'Object' type(String) === 'Function' type(/abc+/) === 'RegExp'
type ( o )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
objId: function (obj) { if (!obj['__id']) { Object.defineProperty(obj, '__id', { value: ++uniqueId }); } return obj['__id']; },
Returns a unique number for the given object. Later calls will still return the same number. @param {Object} obj @returns {number}
objId ( obj )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
clone: function deepClone(o, visited) { visited = visited || {}; var clone; var id; switch (_.util.type(o)) { case 'Object': id = _.util.objId(o); if (visited[id]) { return visited[id]; } clone = /** @type {Record<string, any>} */ ({}); visited[id] = clone; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = deepClone(o[key], visited); } } return /** @type {any} */ (clone); case 'Array': id = _.util.objId(o); if (visited[id]) { return visited[id]; } clone = []; visited[id] = clone; (/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) { clone[i] = deepClone(v, visited); }); return /** @type {any} */ (clone); default: return o; } },
Creates a deep clone of the given object. The main intended use of this function is to clone language definitions. @param {T} o @param {Record<number, any>} [visited] @returns {T} @template T
deepClone ( o , visited )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
getLanguage: function (element) { while (element) { var m = lang.exec(element.className); if (m) { return m[1].toLowerCase(); } element = element.parentElement; } return 'none'; },
Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class. If no language is set for the element or the element is `null` or `undefined`, `none` will be returned. @param {Element} element @returns {string}
getLanguage ( element )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
setLanguage: function (element, language) { // remove all `language-xxxx` classes // (this might leave behind a leading space) element.className = element.className.replace(RegExp(lang, 'gi'), ''); // add the new `language-xxxx` class // (using `classList` will automatically clean up spaces for us) element.classList.add('language-' + language); },
Sets the Prism `language-xxxx` class of the given element. @param {Element} element @param {string} language @returns {void}
setLanguage ( element , language )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
highlightElement: function (element, async, callback) { // Find language var language = _.util.getLanguage(element); var grammar = _.languages[language]; // Set language on the element, if not present _.util.setLanguage(element, language); // Set language on the parent, for styling var parent = element.parentElement; if (parent && parent.nodeName.toLowerCase() === 'pre') { _.util.setLanguage(parent, language); } var code = element.textContent; var env = { element: element, language: language, grammar: grammar, code: code }; function insertHighlightedCode(highlightedCode) { env.highlightedCode = highlightedCode; _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; _.hooks.run('after-highlight', env); _.hooks.run('complete', env); callback && callback.call(env.element); } _.hooks.run('before-sanity-check', env); // plugins may change/add the parent/element parent = env.element.parentElement; if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) { parent.setAttribute('tabindex', '0'); } if (!env.code) { _.hooks.run('complete', env); callback && callback.call(env.element); return; } _.hooks.run('before-highlight', env); if (!env.grammar) { insertHighlightedCode(_.util.encode(env.code)); return; } if (async && _self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function (evt) { insertHighlightedCode(evt.data); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code, immediateClose: true })); } else { insertHighlightedCode(_.highlight(env.code, env.grammar, env.language)); } },
Highlights the code inside a single element. The following hooks will be run: 1. `before-sanity-check` 2. `before-highlight` 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`. 4. `before-insert` 5. `after-highlight` 6. `complete` Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for the element's language. @param {Element} element The element containing the code. It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier. @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default). Note: All language definitions required to highlight the code must be included in the main `prism.js` file for asynchronous highlighting to work. You can build your own bundle on the [Download page](https://prismjs.com/download.html). @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done. Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously. @memberof Prism @public
highlightElement ( element , async , callback )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
highlight: function (text, grammar, language) { var env = { code: text, grammar: grammar, language: language }; _.hooks.run('before-tokenize', env); if (!env.grammar) { throw new Error('The language "' + env.language + '" has no grammar.'); } env.tokens = _.tokenize(env.code, env.grammar); _.hooks.run('after-tokenize', env); return Token.stringify(_.util.encode(env.tokens), env.language); },
Low-level function, only use if you know what you’re doing. It accepts a string of text as input and the language definitions to use, and returns a string with the HTML produced. The following hooks will be run: 1. `before-tokenize` 2. `after-tokenize` 3. `wrap`: On each {@link Token}. @param {string} text A string with the code to be highlighted. @param {Grammar} grammar An object containing the tokens to use. Usually a language definition like `Prism.languages.markup`. @param {string} language The name of the language definition passed to `grammar`. @returns {string} The highlighted HTML. @memberof Prism @public @example Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
highlight ( text , grammar , language )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
tokenize: function (text, grammar) { var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } var tokenList = new LinkedList(); addAfter(tokenList, tokenList.head, text); matchGrammar(text, tokenList, grammar, tokenList.head, 0); return toArray(tokenList); },
This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input and the language definitions to use, and returns an array with the tokenized code. When the language definition includes nested tokens, the function is called recursively on each of these tokens. This method could be useful in other contexts as well, as a very crude parser. @param {string} text A string with the code to be highlighted. @param {Grammar} grammar An object containing the tokens to use. Usually a language definition like `Prism.languages.markup`. @returns {TokenStream} An array of strings and tokens, a token stream. @memberof Prism @public @example let code = `var foo = 0;`; let tokens = Prism.tokenize(code, Prism.languages.javascript); tokens.forEach(token => { if (token instanceof Prism.Token && token.type === 'number') { console.log(`Found numeric literal: ${token.content}`); } });
tokenize ( text , grammar )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); },
Adds the given callback to the list of callbacks for the given hook. The callback will be invoked when the hook it is registered for is run. Hooks are usually directly run by a highlight function but you can also run hooks yourself. One callback function can be registered to multiple hooks and the same hook multiple times. @param {string} name The name of the hook. @param {HookCallback} callback The callback function which is given environment variables. @public
add ( name , callback )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i = 0, callback; (callback = callbacks[i++]);) { callback(env); } }
Runs a hook invoking all registered callbacks with the given environment variables. Callbacks will be invoked synchronously and in the order in which they were registered. @param {string} name The name of the hook. @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered. @public
run ( name , env )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
function Token(type, content, alias, matchedStr) { /** * The type of the token. * * This is usually the key of a pattern in a {@link Grammar}. * * @type {string} * @see GrammarToken * @public */ this.type = type; /** * The strings or tokens contained by this token. * * This will be a token stream if the pattern matched also defined an `inside` grammar. * * @type {string | TokenStream} * @public */ this.content = content; /** * The alias(es) of the token. * * @type {string|string[]} * @see GrammarToken * @public */ this.alias = alias; // Copy of the full string this token was created from this.length = (matchedStr || '').length | 0; }
Creates a new token. @param {string} type See {@link Token#type type} @param {string | TokenStream} content See {@link Token#content content} @param {string|string[]} [alias] The alias(es) of the token. @param {string} [matchedStr=""] A copy of the full string this token was created from. @class @global @public
Token ( type , content , alias , matchedStr )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
function getOrder(element) { while (element) { var order = element.getAttribute('data-toolbar-order'); if (order != null) { order = order.trim(); if (order.length) { return order.split(/\s*,\s*/g); } else { return []; } } element = element.parentElement; } } /** * Post-highlight Prism hook callback. * * @param env */ var hook = Prism.plugins.toolbar.hook = function (env) { // Check if inline or actual code block (credit to line-numbers plugin) var pre = env.element.parentNode; if (!pre || !/pre/i.test(pre.nodeName)) { return; } // Autoloader rehighlights, so only do this once. if (pre.parentNode.classList.contains('code-toolbar')) { return; } // Create wrapper for <pre> to prevent scrolling toolbar with content var wrapper = document.createElement('div'); wrapper.classList.add('code-toolbar'); pre.parentNode.insertBefore(wrapper, pre); wrapper.appendChild(pre); // Setup the toolbar var toolbar = document.createElement('div'); toolbar.classList.add('toolbar'); // order callbacks var elementCallbacks = callbacks; var order = getOrder(env.element); if (order) { elementCallbacks = order.map(function (key) { return map[key] || noop;
Returns the callback order of the given element. @param {HTMLElement} element @returns {string[] | undefined}
Prism.plugins.toolbar.hook ( env )
javascript
colinwilson/lotusdocs
assets/docs/js/prism.js
https://github.com/colinwilson/lotusdocs/blob/master/assets/docs/js/prism.js
MIT
;(function(factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports !== 'undefined') { module.exports = factory(require('jquery')); } else { factory(jQuery); } })(function($) {
jQuery.marquee - scrolling text like old marquee element @author Aamir Afridi - aamirafridi(at)gmail(dot)com / http://aamirafridi.com/jquery/jquery-marquee-plugin
(anonymous) ( factory )
javascript
aamirafridi/jQuery.Marquee
jquery.marquee.js
https://github.com/aamirafridi/jQuery.Marquee/blob/master/jquery.marquee.js
MIT
module.exports = function(root, loadImplementation){ return function register(implementation, opts){ implementation = implementation || null opts = opts || {} // global registration unless explicitly {global: false} in options (default true) var registerGlobal = opts.global !== false; // load any previous global registration if(registered === null && registerGlobal){ registered = root[REGISTRATION_KEY] || null } if(registered !== null && implementation !== null && registered.implementation !== implementation){ // Throw error if attempting to redefine implementation throw new Error('any-promise already defined as "'+registered.implementation+ '". You can only register an implementation before the first '+ ' call to require("any-promise") and an implementation cannot be changed') } if(registered === null){ // use provided implementation if(implementation !== null && typeof opts.Promise !== 'undefined'){ registered = { Promise: opts.Promise, implementation: implementation } } else { // require implementation if implementation is specified but not provided registered = loadImplementation(implementation) } if(registerGlobal){ // register preference globally in case multiple installations root[REGISTRATION_KEY] = registered } } return registered } }
Registers the given implementation. An implementation must be registered prior to any call to `require("any-promise")`, typically on application load. If called with no arguments, will return registration in following priority: For Node.js: 1. Previous registration 2. global.Promise if node.js version >= 0.12 3. Auto detected promise based on first sucessful require of known promise libraries. Note this is a last resort, as the loaded library is non-deterministic. node.js >= 0.12 will always use global.Promise over this priority list. 4. Throws error. For Browser: 1. Previous registration 2. window.Promise 3. Throws error. Options: Promise: Desired Promise constructor global: Boolean - Should the registration be cached in a global variable to allow cross dependency/bundle registration? (default true)
module.exports ( root , loadImplementation )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function loadImplementation(){ if(typeof window.Promise === 'undefined'){ throw new Error("any-promise browser requires a polyfill or explicit registration"+ " e.g: require('any-promise/register/bluebird')") } return { Promise: window.Promise, implementation: 'window.Promise' } }
Browser specific loadImplementation. Always uses `window.Promise` To register a custom implementation, must register with `Promise` option.
loadImplementation ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function asyncify(func) { return (0, _initialParams2.default)(function (args, callback) { var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if ((0, _isObject2.default)(result) && typeof result.then === 'function') { result.then(function (value) { invokeCallback(callback, null, value); }, function (err) { invokeCallback(callback, err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }
Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback. If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. This also means you can asyncify ES2017 `async` functions. @name asyncify @static @memberOf module:Utils @method @alias wrapSync @category Util @param {Function} func - The synchronous function, or Promise-returning function to convert to an {@link AsyncFunction}. @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be invoked with `(args..., callback)`. @example // passing a regular synchronous function async.waterfall([ async.apply(fs.readFile, filename, "utf8"), async.asyncify(JSON.parse), function (data, next) { // data is the result of parsing the text. // If there was a parsing error, it would have been caught. } ], callback); // passing a function returning a promise async.waterfall([ async.apply(fs.readFile, filename, "utf8"), async.asyncify(function (contents) { return db.model.create(contents); }), function (model, next) { // `model` is the instantiated model object. // If there was an error, this function would be skipped. } ], callback); // es2017 example, though `asyncify` is not needed if your JS environment // supports async functions out of the box var q = async.queue(async.asyncify(async function(file) { var intermediateStep = await processFile(file); return await somePromise(intermediateStep) })); q.push(files);
asyncify ( func )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var apply = function(fn/*, ...args*/) { var args = slice(arguments, 1); return function(/*callArgs*/) { var callArgs = slice(arguments); return fn.apply(null, args.concat(callArgs)); }; };
Creates a continuation function with some arguments already applied. Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply. @name apply @static @memberOf module:Utils @method @category Util @param {Function} fn - The function you want to eventually apply all arguments to. Invokes with (arguments...). @param {...*} arguments... - Any number of arguments to automatically apply when the continuation is called. @returns {Function} the partially-applied function @example // using apply async.parallel([ async.apply(fs.writeFile, 'testfile1', 'test1'), async.apply(fs.writeFile, 'testfile2', 'test2') ]); // the same process without using apply async.parallel([ function(callback) { fs.writeFile('testfile1', 'test1', callback); }, function(callback) { fs.writeFile('testfile2', 'test2', callback); } ]); // It's possible to pass any number of additional arguments when calling the // continuation: node> var fn = async.apply(sys.puts, 'one'); node> fn('two', 'three'); one two three
apply ( fn )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); }
Checks if `value` is the [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) @static @memberOf _ @since 0.1.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is an object, else `false`. @example _.isObject({}); // => true _.isObject([1, 2, 3]); // => true _.isObject(_.noop); // => true _.isObject(null); // => false
isObject ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; }
A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. @private @param {*} value The value to query. @returns {string} Returns the raw `toStringTag`.
getRawTag ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function objectToString(value) { return nativeObjectToString$1.call(value); }
Converts `value` to a string using `Object.prototype.toString`. @private @param {*} value The value to convert. @returns {string} Returns the converted string.
objectToString ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); }
The base implementation of `getTag` without fallbacks for buggy environments. @private @param {*} value The value to query. @returns {string} Returns the `toStringTag`.
baseGetTag ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; }
Checks if `value` is classified as a `Function` object. @static @memberOf _ @since 0.1.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is a function, else `false`. @example _.isFunction(_); // => true _.isFunction(/abc/); // => false
isFunction ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; }
Checks if `value` is a valid array-like length. **Note:** This method is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). @static @memberOf _ @since 4.0.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is a valid length, else `false`. @example _.isLength(3); // => true _.isLength(Number.MIN_VALUE); // => false _.isLength(Infinity); // => false _.isLength('3'); // => false
isLength ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); }
Checks if `value` is array-like. A value is considered array-like if it's not a function and has a `value.length` that's an integer greater than or equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. @static @memberOf _ @since 4.0.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is array-like, else `false`. @example _.isArrayLike([1, 2, 3]); // => true _.isArrayLike(document.body.children); // => true _.isArrayLike('abc'); // => true _.isArrayLike(_.noop); // => false
isArrayLike ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function noop() { // No operation performed. }
This method returns `undefined`. @static @memberOf _ @since 2.3.0 @category Util @example _.times(2, _.noop); // => [undefined, undefined]
noop ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; }
The base implementation of `_.times` without support for iteratee shorthands or max array length checks. @private @param {number} n The number of times to invoke `iteratee`. @param {Function} iteratee The function invoked per iteration. @returns {Array} Returns the array of results.
baseTimes ( n , iteratee )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isObjectLike(value) { return value != null && typeof value == 'object'; }
Checks if `value` is object-like. A value is object-like if it's not `null` and has a `typeof` result of "object". @static @memberOf _ @since 4.0.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is object-like, else `false`. @example _.isObjectLike({}); // => true _.isObjectLike([1, 2, 3]); // => true _.isObjectLike(_.noop); // => false _.isObjectLike(null); // => false
isObjectLike ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; }
The base implementation of `_.isArguments`. @private @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is an `arguments` object,
baseIsArguments ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
Checks if `value` is likely an `arguments` object. @static @memberOf _ @since 0.1.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is an `arguments` object, else `false`. @example _.isArguments(function() { return arguments; }()); // => true _.isArguments([1, 2, 3]); // => false
(anonymous) ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function stubFalse() { return false; }
This method returns `false`. @static @memberOf _ @since 4.13.0 @category Util @returns {boolean} Returns `false`. @example _.times(2, _.stubFalse); // => [false, false]
stubFalse ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER$1 : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); }
Checks if `value` is a valid array-like index. @private @param {*} value The value to check. @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
isIndex ( value , length )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; }
The base implementation of `_.isTypedArray` without Node.js optimizations. @private @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
baseIsTypedArray ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseUnary(func) { return function(value) { return func(value); }; }
The base implementation of `_.unary` without support for storing metadata. @private @param {Function} func The function to cap arguments for. @returns {Function} Returns the new capped function.
baseUnary ( func )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$1.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; }
Creates an array of the enumerable property names of the array-like `value`. @private @param {*} value The value to query. @param {boolean} inherited Specify returning inherited property names. @returns {Array} Returns the array of property names.
arrayLikeKeys ( value , inherited )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; return value === proto; }
Checks if `value` is likely a prototype object. @private @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
isPrototype ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; }
Creates a unary function that invokes `func` with its argument transformed. @private @param {Function} func The function to wrap. @param {Function} transform The argument transform. @returns {Function} Returns the new function.
overArg ( func , transform )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$3.call(object, key) && key != 'constructor') { result.push(key); } } return result; }
The base implementation of `_.keys` which doesn't treat sparse arrays as dense. @private @param {Object} object The object to query. @returns {Array} Returns the array of property names.
baseKeys ( object )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); }
Creates an array of the own enumerable property names of `object`. **Note:** Non-object values are coerced to objects. See the [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) for more details. @static @since 0.1.0 @memberOf _ @category Object @param {Object} object The object to query. @returns {Array} Returns the array of property names. @example function Foo() { this.a = 1; this.b = 2; } Foo.prototype.c = 3; _.keys(new Foo); // => ['a', 'b'] (iteration order is not guaranteed) _.keys('hi'); // => ['0', '1']
keys ( object )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function eachOfLimit(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); }
The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a time. @name eachOfLimit @static @memberOf module:Collections @method @see [async.eachOf]{@link module:Collections.eachOf} @alias forEachOfLimit @category Collection @param {Array|Iterable|Object} coll - A collection to iterate over. @param {number} limit - The maximum number of async operations at a time. @param {AsyncFunction} iteratee - An async function to apply to each item in `coll`. The `key` is the item's key, or index in the case of an array. Invoked with (item, key, callback). @param {Function} [callback] - A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err).
eachOfLimit ( coll , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var eachOf = function(coll, iteratee, callback) { var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; eachOfImplementation(coll, wrapAsync(iteratee), callback); };
Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument to the iteratee. @name eachOf @static @memberOf module:Collections @method @alias forEachOf @category Collection @see [async.each]{@link module:Collections.each} @param {Array|Iterable|Object} coll - A collection to iterate over. @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. The `key` is the item's key, or index in the case of an array. Invoked with (item, key, callback). @param {Function} [callback] - A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). @example var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; var configs = {}; async.forEachOf(obj, function (value, key, callback) { fs.readFile(__dirname + value, "utf8", function (err, data) { if (err) return callback(err); try { configs[key] = JSON.parse(data); } catch (e) { return callback(e); } callback(); }); }, function (err) { if (err) console.error(err.message); // configs is now a map of JSON data doSomethingWith(configs); });
eachOf ( coll , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; }
A specialized version of `_.forEach` for arrays without support for iteratee shorthands. @private @param {Array} [array] The array to iterate over. @param {Function} iteratee The function invoked per iteration. @returns {Array} Returns `array`.
arrayEach ( array , iteratee )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; }
Creates a base function for methods like `_.forIn` and `_.forOwn`. @private @param {boolean} [fromRight] Specify iterating from right to left. @returns {Function} Returns the new base function.
createBaseFor ( fromRight )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); }
The base implementation of `_.forOwn` without support for iteratee shorthands. @private @param {Object} object The object to iterate over. @param {Function} iteratee The function invoked per iteration. @returns {Object} Returns `object`.
baseForOwn ( object , iteratee )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); }
Casts `array` to a slice if it's needed. @private @param {Array} array The array to inspect. @param {number} start The start position. @param {number} [end=array.length] The end position. @returns {Array} Returns the cast slice.
castSlice ( array , start , end )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; }
Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol that is not found in the character symbols. @private @param {Array} strSymbols The string symbols to inspect. @param {Array} chrSymbols The character symbols to find. @returns {number} Returns the index of the last unmatched string symbol.
charsEndIndex ( strSymbols , chrSymbols )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; }
Used by `_.trim` and `_.trimStart` to get the index of the first string symbol that is not found in the character symbols. @private @param {Array} strSymbols The string symbols to inspect. @param {Array} chrSymbols The character symbols to find. @returns {number} Returns the index of the first unmatched string symbol.
charsStartIndex ( strSymbols , chrSymbols )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function asciiToArray(string) { return string.split(''); }
Converts an ASCII `string` to an array. @private @param {string} string The string to convert. @returns {Array} Returns the converted array.
asciiToArray ( string )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function hasUnicode(string) { return reHasUnicode.test(string); }
Checks if `string` contains Unicode symbols. @private @param {string} string The string to inspect. @returns {boolean} Returns `true` if a symbol is found, else `false`.
hasUnicode ( string )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function unicodeToArray(string) { return string.match(reUnicode) || []; }
Converts a Unicode `string` to an array. @private @param {string} string The string to convert. @returns {Array} Returns the converted array.
unicodeToArray ( string )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); }
Converts `string` to an array. @private @param {string} string The string to convert. @returns {Array} Returns the converted array.
stringToArray ( string )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function toString(value) { return value == null ? '' : baseToString(value); }
Converts `value` to a string. An empty string is returned for `null` and `undefined` values. The sign of `-0` is preserved. @static @memberOf _ @since 4.0.0 @category Lang @param {*} value The value to convert. @returns {string} Returns the converted string. @example _.toString(null); // => '' _.toString(-0); // => '-0' _.toString([1, 2, 3]); // => '1,2,3'
toString ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); }
Removes leading and trailing whitespace or specified characters from `string`. @static @memberOf _ @since 3.0.0 @category String @param {string} [string=''] The string to trim. @param {string} [chars=whitespace] The characters to trim. @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. @returns {string} Returns the trimmed string. @example _.trim(' abc '); // => 'abc' _.trim('-_-abc-_-', '_-'); // => 'abc' _.map([' foo ', ' bar '], _.trim); // => ['foo', 'bar']
trim ( string , chars , guard )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function cargo(worker, payload) { return queue(worker, 1, payload); }
Creates a `cargo` object with the specified payload. Tasks added to the cargo will be processed altogether (up to the `payload` limit). If the `worker` is in progress, the task is queued until it becomes available. Once the `worker` has completed some tasks, each callback of those tasks is called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work. While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers at a time, cargo passes an array of tasks to a single worker, repeating when the worker is finished. @name cargo @static @memberOf module:ControlFlow @method @see [async.queue]{@link module:ControlFlow.queue} @category Control Flow @param {AsyncFunction} worker - An asynchronous function for processing an array of queued tasks. Invoked with `(tasks, callback)`. @param {number} [payload=Infinity] - An optional `integer` for determining how many tasks should be processed per round; if omitted, the default is unlimited. @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can attached as certain properties to listen for specific events during the lifecycle of the cargo and inner queue. @example // create a cargo object with payload 2 var cargo = async.cargo(function(tasks, callback) { for (var i=0; i<tasks.length; i++) { console.log('hello ' + tasks[i].name); } callback(); }, 2); // add some items cargo.push({name: 'foo'}, function(err) { console.log('finished processing foo'); }); cargo.push({name: 'bar'}, function(err) { console.log('finished processing bar'); }); cargo.push({name: 'baz'}, function(err) { console.log('finished processing baz'); });
cargo ( worker , payload )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function reduce(coll, memo, iteratee, callback) { callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); eachOfSeries(coll, function(x, i, callback) { _iteratee(memo, x, function(err, v) { memo = v; callback(err); }); }, function(err) { callback(err, memo); }); }
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|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 complete 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). @example async.reduce([1,2,3], 0, function(memo, item, callback) { // pointless async: process.nextTick(function() { callback(null, memo + item) }); }, function(err, result) { // result is now equal to the last value of memo, which is 6 });
reduce ( coll , memo , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function seq(/*...functions*/) { var _functions = arrayMap(arguments, wrapAsync); return function(/*...args*/) { var args = slice(arguments); var that = this; var cb = args[args.length - 1]; if (typeof cb == 'function') { args.pop(); } else { cb = noop; } reduce(_functions, args, function(newargs, fn, cb) { fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { var nextargs = slice(arguments, 1); cb(err, nextargs); })); }, function(err, results) { cb.apply(that, [err].concat(results)); }); }; }
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( _.bind(User.get, 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 }); } }); });
seq ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var compose = function(/*...args*/) { return seq.apply(null, slice(arguments).reverse()); };
Creates a function which is a composition of the passed asynchronous functions. Each function consumes the return value of the function that follows. Composing functions `f()`, `g()`, and `h()` would produce the result of `f(g(h()))`, only this version uses callbacks to obtain the return values. Each function is executed with the `this` binding of the composed function. @name compose @static @memberOf module:ControlFlow @method @category Control Flow @param {...AsyncFunction} functions - the asynchronous functions to compose @returns {Function} an asynchronous function that is the composed asynchronous `functions` @example function add1(n, callback) { setTimeout(function () { callback(null, n + 1); }, 10); } function mul3(n, callback) { setTimeout(function () { callback(null, n * 3); }, 10); } var add1mul3 = async.compose(mul3, add1); add1mul3(4, function (err, result) { // result now equals 15 });
compose ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var concatLimit = function(coll, limit, iteratee, callback) { callback = callback || noop; var _iteratee = wrapAsync(iteratee); mapLimit(coll, limit, function(val, callback) { _iteratee(val, function(err /*, ...args*/) { if (err) return callback(err); return callback(null, slice(arguments, 1)); }); }, function(err, mapResults) { var result = []; for (var i = 0; i < mapResults.length; i++) { if (mapResults[i]) { result = _concat.apply(result, mapResults[i]); } } return callback(err, result); }); };
The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. @name concatLimit @static @memberOf module:Collections @method @see [async.concat]{@link module:Collections.concat} @category Collection @param {Array|Iterable|Object} coll - 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 item in `coll`, which should use an array 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 an array containing the concatenated results of the `iteratee` function. Invoked with (err, results).
concatLimit ( coll , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var constant = function(/*...values*/) { var values = slice(arguments); var args = [null].concat(values); return function (/*...ignoredArgs, callback*/) { var callback = arguments[arguments.length - 1]; return callback.apply(this, args); }; };
Returns a function that when called, calls-back with the values provided. Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to [`auto`]{@link module:ControlFlow.auto}. @name constant @static @memberOf module:Utils @method @category Util @param {...*} arguments... - Any number of arguments to automatically invoke callback with. @returns {AsyncFunction} Returns a function that when invoked, automatically invokes the callback with the previous given arguments. @example async.waterfall([ async.constant(42), function (value, next) { // value === 42 }, //... ], callback); async.waterfall([ async.constant(filename, "utf8"), fs.readFile, function (fileData, next) { //... } //... ], callback); async.auto({ hostname: async.constant("https://server.net/"), port: findFreePort, launchServer: ["hostname", "port", function (options, cb) { startServer(options, cb); }], //... }, callback);
constant ( )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function identity(value) { return value; }
This method returns the first argument it receives. @static @since 0.1.0 @memberOf _ @category Util @param {*} value Any value. @returns {*} Returns `value`. @example var object = { 'a': 1 }; console.log(_.identity(object) === object); // => true
identity ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function doDuring(fn, test, callback) { callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); function next(err/*, ...args*/) { if (err) return callback(err); var args = slice(arguments, 1); args.push(check); _test.apply(this, args); } function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } check(null, true); }
The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in the order of operations, the arguments `test` and `fn` are switched. Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. @name doDuring @static @memberOf module:ControlFlow @method @see [async.during]{@link module:ControlFlow.during} @category Control Flow @param {AsyncFunction} fn - An async function which is called each time `test` passes. Invoked with (callback). @param {AsyncFunction} test - asynchronous truth test to perform before each execution of `fn`. Invoked with (...args, callback), where `...args` are the non-error args from the previous callback of `fn`. @param {Function} [callback] - A callback which is called after the test function has failed and repeated execution of `fn` has stopped. `callback` will be passed an error if one occurred, otherwise `null`.
doDuring ( fn , test , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function doWhilst(iteratee, test, callback) { callback = onlyOnce(callback || noop); var _iteratee = wrapAsync(iteratee); var next = function(err/*, ...args*/) { if (err) return callback(err); var args = slice(arguments, 1); if (test.apply(this, args)) return _iteratee(next); callback.apply(null, [null].concat(args)); }; _iteratee(next); }
The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in the order of operations, the arguments `test` and `iteratee` are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. @name doWhilst @static @memberOf module:ControlFlow @method @see [async.whilst]{@link module:ControlFlow.whilst} @category Control Flow @param {AsyncFunction} iteratee - A function which is called each time `test` passes. Invoked with (callback). @param {Function} test - synchronous truth test to perform after each execution of `iteratee`. Invoked with any non-error callback results of `iteratee`. @param {Function} [callback] - A callback which is called after the test function has failed 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]);
doWhilst ( iteratee , test , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function doUntil(iteratee, test, callback) { doWhilst(iteratee, function() { return !test.apply(this, arguments); }, callback); }
Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the argument ordering differs from `until`. @name doUntil @static @memberOf module:ControlFlow @method @see [async.doWhilst]{@link module:ControlFlow.doWhilst} @category Control Flow @param {AsyncFunction} iteratee - An async function which is called each time `test` fails. Invoked with (callback). @param {Function} test - synchronous truth test to perform after each execution of `iteratee`. Invoked with any non-error callback results of `iteratee`. @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]);
doUntil ( iteratee , test , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function during(test, fn, callback) { callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); function next(err) { if (err) return callback(err); _test(check); } function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } _test(check); }
Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error. @name during @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 `fn`. Invoked with (callback). @param {AsyncFunction} fn - An async function which is called each time `test` passes. Invoked with (callback). @param {Function} [callback] - A callback which is called after the test function has failed and repeated execution of `fn` has stopped. `callback` will be passed an error, if one occurred, otherwise `null`. @example var count = 0; async.during( function (callback) { return callback(null, count < 5); }, function (callback) { count++; setTimeout(callback, 1000); }, function (err) { // 5 seconds have passed } );
during ( test , fn , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function eachLimit(coll, iteratee, callback) { eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); }
Applies the function `iteratee` to each item in `coll`, in parallel. The `iteratee` is called with an item from the list, and a callback for when it has finished. If the `iteratee` passes an error to its `callback`, the main `callback` (for the `each` function) is immediately called with the error. Note, that since this function applies `iteratee` to each item in parallel, there is no guarantee that the iteratee functions will complete in order. @name each @static @memberOf module:Collections @method @alias forEach @category Collection @param {Array|Iterable|Object} coll - A collection to iterate over. @param {AsyncFunction} iteratee - An async function to apply to each item in `coll`. Invoked with (item, callback). The array index is not passed to the iteratee. If you need the index, use `eachOf`. @param {Function} [callback] - A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err). @example // assuming openFiles is an array of file names and saveFile is a function // to save the modified contents of that file: async.each(openFiles, saveFile, function(err){ // if any of the saves produced an error, err would equal that error }); // assuming openFiles is an array of file names async.each(openFiles, function(file, callback) { // Perform operation on file here. console.log('Processing file ' + file); if( file.length > 32 ) { console.log('This file name is too long'); callback('File name too long'); } else { // Do work to process file here console.log('File processed'); callback(); } }, function(err) { // if any of the file processing produced an error, err would equal that error if( err ) { // One of the iterations produced an error. // All processing will now stop. console.log('A file failed to process'); } else { console.log('All files have been processed successfully'); } });
eachLimit ( coll , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function eachLimit$1(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); }
The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. @name eachLimit @static @memberOf module:Collections @method @see [async.each]{@link module:Collections.each} @alias forEachLimit @category Collection @param {Array|Iterable|Object} coll - A collection to iterate over. @param {number} limit - The maximum number of async operations at a time. @param {AsyncFunction} iteratee - An async function to apply to each item in `coll`. The array index is not passed to the iteratee. If you need the index, use `eachOfLimit`. Invoked with (item, callback). @param {Function} [callback] - A callback which is called when all `iteratee` functions have finished, or an error occurs. Invoked with (err).
$1 ( coll , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function ensureAsync(fn) { if (isAsync(fn)) return fn; return initialParams(function (args, callback) { var sync = true; args.push(function () { var innerArgs = arguments; if (sync) { setImmediate$1(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); fn.apply(this, args); sync = false; }); }
Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. ES2017 `async` functions are returned as-is -- they are immune to Zalgo's corrupting influences, as they always resolve on a later tick. @name ensureAsync @static @memberOf module:Utils @method @category Util @param {AsyncFunction} fn - an async function, one that expects a node-style callback as its last argument. @returns {AsyncFunction} Returns a wrapped function with the exact same call signature as the function passed in. @example function sometimesAsync(arg, callback) { if (cache[arg]) { return callback(null, cache[arg]); // this would be synchronous!! } else { doSomeIO(arg, callback); // this IO would be asynchronous } } // this has a risk of stack overflows if many results are cached in a row async.mapSeries(args, sometimesAsync, done); // this will defer sometimesAsync's callback if necessary, // preventing stack overflows async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
ensureAsync ( fn )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; }
The base implementation of `_.property` without support for deep paths. @private @param {string} key The key of the property to get. @returns {Function} Returns the new accessor function.
baseProperty ( key )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var groupByLimit = function(coll, limit, iteratee, callback) { callback = callback || noop; var _iteratee = wrapAsync(iteratee); mapLimit(coll, limit, function(val, callback) { _iteratee(val, function(err, key) { if (err) return callback(err); return callback(null, {key: key, val: val}); }); }, function(err, mapResults) { var result = {}; // from MDN, handle object having an `hasOwnProperty` prop var hasOwnProperty = Object.prototype.hasOwnProperty; for (var i = 0; i < mapResults.length; i++) { if (mapResults[i]) { var key = mapResults[i].key; var val = mapResults[i].val; if (hasOwnProperty.call(result, key)) { result[key].push(val); } else { result[key] = [val]; } } } return callback(err, result); }); };
The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. @name groupByLimit @static @memberOf module:Collections @method @see [async.groupBy]{@link module:Collections.groupBy} @category Collection @param {Array|Iterable|Object} coll - A collection to iterate over. @param {number} limit - The maximum number of async operations at a time. @param {AsyncFunction} iteratee - An async function to apply to each item in `coll`. The iteratee should complete with a `key` to group the value under. Invoked with (value, callback). @param {Function} [callback] - A callback which is called when all `iteratee` functions have finished, or an error occurs. Result is an `Object` whoses properties are arrays of values which returned the corresponding key.
groupByLimit ( coll , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function mapValuesLimit(obj, limit, iteratee, callback) { callback = once(callback || noop); var newObj = {}; var _iteratee = wrapAsync(iteratee); eachOfLimit(obj, limit, function(val, key, next) { _iteratee(val, key, function (err, result) { if (err) return next(err); newObj[key] = result; next(); }); }, function (err) { callback(err, newObj); }); }
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).
mapValuesLimit ( obj , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function memoize(fn, hasher) { var memo = Object.create(null); var queues = Object.create(null); hasher = hasher || identity; var _fn = wrapAsync(fn); var memoized = initialParams(function memoized(args, callback) { var key = hasher.apply(null, args); if (has(memo, key)) { setImmediate$1(function() { callback.apply(null, memo[key]); }); } else if (has(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; _fn.apply(null, args.concat(function(/*args*/) { var args = slice(arguments); memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }
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. 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 });
memoize ( fn , hasher )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function parallelLimit(tasks, callback) { _parallel(eachOf, tasks, callback); }
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|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). @example async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ], // optional callback function(err, results) { // the results array will equal ['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) { // results is now equals to: {one: 1, two: 2} });
parallelLimit ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function parallelLimit$1(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }
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|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).
$1 ( tasks , limit , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var queue$1 = function (worker, concurrency) { var _worker = wrapAsync(worker); return queue(function (items, cb) { _worker(items[0], cb); }, concurrency, 1); };
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 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'); }; // add some items to the queue q.push({name: 'foo'}, function(err) { console.log('finished processing foo'); }); q.push({name: 'bar'}, function (err) { console.log('finished processing 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'); });
$1 ( worker , concurrency )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var priorityQueue = function(worker, concurrency) { // Start with a normal queue var q = queue$1(worker, concurrency); // Override push to accept second parameter representing priority q.push = function(data, priority, callback) { if (callback == null) callback = noop; if (typeof callback !== 'function') { throw new Error('task callback must be a function'); } q.started = true; if (!isArray(data)) { data = [data]; } if (data.length === 0) { // call drain immediately if there are no tasks return setImmediate$1(function() { q.drain(); }); } priority = priority || 0; var nextNode = q._tasks.head; while (nextNode && priority >= nextNode.priority) { nextNode = nextNode.next; } for (var i = 0, l = data.length; i < l; i++) { var item = { data: data[i], priority: priority, callback: callback }; if (nextNode) { q._tasks.insertBefore(nextNode, item); } else { q._tasks.push(item); } } setImmediate$1(q.process); }; // Remove unshift function delete q.unshift; return q; };
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 two 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. * The `unshift` method was removed.
priorityQueue ( worker , concurrency )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function race(tasks, callback) { callback = once(callback || noop); if (!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++) { wrapAsync(tasks[i])(callback); } }
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 undefined @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 });
race ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function reduceRight (array, memo, iteratee, callback) { var reversed = slice(array).reverse(); reduce(reversed, memo, iteratee, callback); }
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 complete 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).
reduceRight ( array , memo , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function reflect(fn) { var _fn = wrapAsync(fn); return initialParams(function reflectOn(args, reflectCallback) { args.push(function callback(error, cbArg) { if (error) { reflectCallback(null, { error: error }); } else { var value; if (arguments.length <= 2) { value = cbArg; } else { value = slice(arguments, 1); } reflectCallback(null, { value: value }); } }); return _fn.apply(this, args); }); }
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' });
reflect ( fn )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function reflectAll(tasks) { var results; if (isArray(tasks)) { results = arrayMap(tasks, reflect); } else { results = {}; baseForOwn(tasks, function(task, key) { results[key] = reflect.call(this, task); }); } return results; }
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' });
reflectAll ( tasks )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function constant$1(value) { return function() { return value; }; }
Creates a function that returns `value`. @static @memberOf _ @since 2.4.0 @category Util @param {*} value The value to return from the new function. @returns {Function} Returns the new constant function. @example var objects = _.times(2, _.constant({ 'a': 1 })); console.log(objects); // => [{ 'a': 1 }, { 'a': 1 }] console.log(objects[0] === objects[1]); // => true
$1 ( value )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var retryable = function (opts, task) { if (!task) { task = opts; opts = null; } var _task = wrapAsync(task); return initialParams(function (args, callback) { function taskFn(cb) { _task.apply(null, args.concat(cb)); } if (opts) retry(opts, taskFn, callback); else retry(taskFn, callback); }); };
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` @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);
retryable ( opts , task )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function series(tasks, callback) { _parallel(eachOfSeries, tasks, callback); }
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|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). @example async.series([ function(callback) { // do some stuff ... callback(null, 'one'); }, function(callback) { // do some more stuff ... callback(null, 'two'); } ], // optional callback function(err, results) { // results is now equal to ['one', 'two'] }); async.series({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function() { callback(null, 2); }, 100); } }, function(err, results) { // results is now equal to: {one: 1, two: 2} });
series ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); map(coll, function (x, callback) { _iteratee(x, function (err, criteria) { if (err) return callback(err); callback(null, {value: x, criteria: criteria}); }); }, function (err, results) { if (err) return callback(err); callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }
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|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). @example async.sortBy(['file1','file2','file3'], function(file, callback) { fs.stat(file, function(err, stats) { callback(err, stats.mtime); }); }, function(err, results) { // results is now the original array of files sorted by // modified date }); // By modifying the callback parameter the // sorting order can be influenced: // ascending order async.sortBy([1,9,3,5], function(x, callback) { callback(null, x); }, function(err,result) { // result callback }); // descending order async.sortBy([1,9,3,5], function(x, callback) { callback(null, x*-1); //<- x*-1 instead of x, turns the order around }, function(err,result) { // result callback });
sortBy ( coll , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function timeout(asyncFn, milliseconds, info) { var fn = wrapAsync(asyncFn); return initialParams(function (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(function () { if (!timedOut) { callback.apply(null, arguments); clearTimeout(timer); } }); // setup timer and call original function timer = setTimeout(timeoutCallback, milliseconds); fn.apply(null, args); }); }
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' });
timeout ( asyncFn , milliseconds , info )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; }
The base implementation of `_.range` and `_.rangeRight` which doesn't coerce arguments. @private @param {number} start The start of the range. @param {number} end The end of the range. @param {number} step The value to increment or decrement by. @param {boolean} [fromRight] Specify iterating from right to left. @returns {Array} Returns the range of numbers.
baseRange ( start , end , step , fromRight )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function timeLimit(count, limit, iteratee, callback) { var _iteratee = wrapAsync(iteratee); mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); }
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}.
timeLimit ( count , limit , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3) { callback = iteratee; iteratee = accumulator; accumulator = isArray(coll) ? [] : {}; } callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); eachOf(coll, function(v, k, cb) { _iteratee(accumulator, v, k, cb); }, function(err) { callback(err, accumulator); }); }
A relative of `reduce`. Takes an Object or Array, and iterates over each element in series, 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|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). @example async.transform([1,2,3], function(acc, item, index, callback) { // pointless async: process.nextTick(function() { acc.push(item * 2) callback(null) }); }, function(err, result) { // result is now equal to [2, 4, 6] }); @example async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { setImmediate(function () { obj[key] = val * 2; callback(); }) }, function (err, result) { // result is equal to {a: 2, b: 4, c: 6} })
transform ( coll , accumulator , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function tryEach(tasks, callback) { var error = null; var result; callback = callback || noop; eachSeries(tasks, function(task, callback) { wrapAsync(task)(function (err, res/*, ...args*/) { if (arguments.length > 2) { result = slice(arguments, 1); } else { result = res; } error = err; callback(!err); }); }, function () { callback(error, result); }); }
It runs each task in series but stops whenever any of the functions were successful. If one of the tasks were successful, the `callback` will be passed the result of the successful task. If all tasks fail, the callback will be passed the error and result (if any) of the final attempt. @name tryEach @static @memberOf module:ControlFlow @method @category Control Flow @param {Array|Iterable|Object} tasks - A collection containing functions to run, each function is passed a `callback(err, result)` it must call on completion with an error `err` (which can be `null`) and an optional `result` value. @param {Function} [callback] - An optional callback which is called when one of the tasks has succeeded, or all have failed. It receives the `err` and `result` arguments of the last attempt at completing the `task`. Invoked with (err, results). @example async.tryEach([ function getDataFromFirstWebsite(callback) { // Try getting the data from the first website callback(err, data); }, function getDataFromSecondWebsite(callback) { // First website failed, // Try getting the data from the backup website callback(err, data); } ], // optional callback function(err, results) { Now do something with the data. });
tryEach ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function unmemoize(fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }
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
unmemoize ( fn )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function whilst(test, iteratee, callback) { callback = onlyOnce(callback || noop); var _iteratee = wrapAsync(iteratee); if (!test()) return callback(null); var next = function(err/*, ...args*/) { if (err) return callback(err); if (test()) return _iteratee(next); var args = slice(arguments, 1); callback.apply(null, [null].concat(args)); }; _iteratee(next); }
Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when stopped, or an error occurs. @name whilst @static @memberOf module:ControlFlow @method @category Control Flow @param {Function} test - synchronous truth test to perform before each execution of `iteratee`. Invoked with (). @param {AsyncFunction} iteratee - An async function which is called each time `test` passes. Invoked with (callback). @param {Function} [callback] - A callback which is called after the test function has failed 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 undefined @example var count = 0; async.whilst( function() { return count < 5; }, function(callback) { count++; setTimeout(function() { callback(null, count); }, 1000); }, function (err, n) { // 5 seconds have passed, n = 5 } );
whilst ( test , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function until(test, iteratee, callback) { whilst(function() { return !test.apply(this, arguments); }, iteratee, callback); }
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 {Function} test - synchronous truth test to perform before each execution of `iteratee`. Invoked with (). @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]);
until ( test , iteratee , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
var waterfall = function(tasks, callback) { callback = once(callback || noop); if (!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 = wrapAsync(tasks[taskIndex++]); args.push(onlyOnce(next)); task.apply(null, args); } function next(err/*, ...args*/) { if (err || taskIndex === tasks.length) { return callback.apply(null, arguments); } nextTask(slice(arguments, 1)); } nextTask([]); };
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 undefined @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'); }
waterfall ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function retry(opts, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var options = { times: DEFAULT_TIMES, intervalFunc: constant$1(DEFAULT_INTERVAL) }; function parseTimes(acc, t) { if (typeof t === 'object') { acc.times = +t.times || DEFAULT_TIMES; acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+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"); } } if (arguments.length < 3 && typeof opts === 'function') { callback = task || noop; task = opts; } else { parseTimes(options, opts); callback = callback || noop; } if (typeof task !== 'function') { throw new Error("Invalid arguments for async.retry"); } var _task = wrapAsync(task); var attempt = 1; function retryAttempt() { _task(function(err) { if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { setTimeout(retryAttempt, options.intervalFunc(attempt)); } else { callback.apply(null, arguments); } }); } retryAttempt(); } /** * 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` * @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); */ var retryable = function (opts, task) { if (!task) { task = opts; opts = null; } var _task = wrapAsync(task); return initialParams(function (args, callback) { function taskFn(cb) { _task.apply(null, args.concat(cb)); } if (opts) retry(opts, taskFn, callback); else retry(taskFn, callback); }); }; /** * 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|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). * @example * async.series([ * function(callback) { * // do some stuff ... * callback(null, 'one'); * }, * function(callback) { * // do some more stuff ... * callback(null, 'two'); * } * ], * // optional callback * function(err, results) { * // results is now equal to ['one', 'two'] * }); * * async.series({ * one: function(callback) { * setTimeout(function() { * callback(null, 1); * }, 200); * }, * two: function(callback){ * setTimeout(function() { * callback(null, 2); * }, 100); * } * }, function(err, results) { * // results is now equal to: {one: 1, two: 2} * }); */ function series(tasks, callback) { _parallel(eachOfSeries, tasks, callback); } /** * 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|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). * @example * * async.some(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, result) { * // if result is true then at least one of the files exists * }); */ var some = doParallel(_createTester(Boolean, identity)); /** * 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|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). */ var someLimit = doParallelLimit(_createTester(Boolean, identity)); /** * 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|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). */ var someSeries = doLimit(someLimit, 1); /** * 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|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). * @example * * async.sortBy(['file1','file2','file3'], function(file, callback) { * fs.stat(file, function(err, stats) { * callback(err, stats.mtime); * }); * }, function(err, results) { * // results is now the original array of files sorted by * // modified date * }); * * // By modifying the callback parameter the * // sorting order can be influenced: * * // ascending order * async.sortBy([1,9,3,5], function(x, callback) { * callback(null, x); * }, function(err,result) { * // result callback * }); * * // descending order * async.sortBy([1,9,3,5], function(x, callback) { * callback(null, x*-1); //<- x*-1 instead of x, turns the order around * }, function(err,result) { * // result callback * }); */ function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); map(coll, function (x, callback) { _iteratee(x, function (err, criteria) { if (err) return callback(err); callback(null, {value: x, criteria: criteria}); }); }, function (err, results) { if (err) return callback(err); callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } } /** * 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 = wrapAsync(asyncFn); return initialParams(function (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(function () { if (!timedOut) { callback.apply(null, arguments); clearTimeout(timer); } }); // setup timer and call original function timer = setTimeout(timeoutCallback, milliseconds); fn.apply(null, args); }); } /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; var nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * 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}. */ function timeLimit(count, limit, iteratee, callback) { var _iteratee = wrapAsync(iteratee); mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); } /** * 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}. * @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 * }); */ var times = doLimit(timeLimit, Infinity); /** * 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}. */ var timesSeries = doLimit(timeLimit, 1); /** * A relative of `reduce`. Takes an Object or Array, and iterates over each * element in series, 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|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). * @example * * async.transform([1,2,3], function(acc, item, index, callback) { * // pointless async: * process.nextTick(function() { * acc.push(item * 2) * callback(null) * }); * }, function(err, result) { * // result is now equal to [2, 4, 6] * }); * * @example * * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { * setImmediate(function () { * obj[key] = val * 2; * callback(); * }) * }, function (err, result) { * // result is equal to {a: 2, b: 4, c: 6} * }) */ function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3) { callback = iteratee; iteratee = accumulator; accumulator = isArray(coll) ? [] : {}; } callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); eachOf(coll, function(v, k, cb) { _iteratee(accumulator, v, k, cb); }, function(err) { callback(err, accumulator); }); } /** * It runs each task in series but stops whenever any of the functions were * successful. If one of the tasks were successful, the `callback` will be * passed the result of the successful task. If all tasks fail, the callback * will be passed the error and result (if any) of the final attempt. * * @name tryEach * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Array|Iterable|Object} tasks - A collection containing functions to * run, each function is passed a `callback(err, result)` it must call on * completion with an error `err` (which can be `null`) and an optional `result` * value. * @param {Function} [callback] - An optional callback which is called when one * of the tasks has succeeded, or all have failed. It receives the `err` and * `result` arguments of the last attempt at completing the `task`. Invoked with * (err, results). * @example * async.tryEach([ * function getDataFromFirstWebsite(callback) { * // Try getting the data from the first website * callback(err, data); * }, * function getDataFromSecondWebsite(callback) { * // First website failed, * // Try getting the data from the backup website * callback(err, data); * } * ], * // optional callback * function(err, results) { * Now do something with the data. * }); * */ function tryEach(tasks, callback) { var error = null; var result; callback = callback || noop; eachSeries(tasks, function(task, callback) { wrapAsync(task)(function (err, res/*, ...args*/) { if (arguments.length > 2) { result = slice(arguments, 1); } else { result = res; } error = err; callback(!err); }); }, function () { callback(error, result); }); } /** * 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 function () { return (fn.unmemoized || fn).apply(null, arguments); }; } /** * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when * stopped, or an error occurs. * * @name whilst * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Function} test - synchronous truth test to perform before each * execution of `iteratee`. Invoked with (). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test * function has failed 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 undefined * @example * * var count = 0; * async.whilst( * function() { return count < 5; }, * function(callback) { * count++; * setTimeout(function() { * callback(null, count); * }, 1000); * }, * function (err, n) { * // 5 seconds have passed, n = 5 * } * ); */ function whilst(test, iteratee, callback) { callback = onlyOnce(callback || noop); var _iteratee = wrapAsync(iteratee); if (!test()) return callback(null); var next = function(err/*, ...args*/) { if (err) return callback(err); if (test()) return _iteratee(next); var args = slice(arguments, 1); callback.apply(null, [null].concat(args)); }; _iteratee(next); } /** * 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 {Function} test - synchronous truth test to perform before each * execution of `iteratee`. Invoked with (). * @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]); */ function until(test, iteratee, callback) { whilst(function() { return !test.apply(this, arguments); }, iteratee, callback); } /** * 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 undefined * @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'); * } */ var waterfall = function(tasks, callback) { callback = once(callback || noop); if (!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 = wrapAsync(tasks[taskIndex++]); args.push(onlyOnce(next)); task.apply(null, args); } function next(err/*, ...args*/) { if (err || taskIndex === tasks.length) { return callback.apply(null, arguments); } nextTask(slice(arguments, 1)); } nextTask([]); }; /** * An "async function" in the context of Async is an asynchronous function with * a variable number of parameters, with the final parameter being a callback. * (`function (arg1, arg2, ..., callback) {}`) * The final callback is of the form `callback(err, results...)`, which must be * called once the function is completed. The callback should be called with a * Error as its first argument to signal that an error occurred. * Otherwise, if no error occurred, it should be called with `null` as the first * argument, and any additional `result` arguments that may apply, to signal * successful completion. * The callback must be called exactly once, ideally on a later tick of the * JavaScript event loop. * * This type of function is also referred to as a "Node-style async function", * or a "continuation passing-style function" (CPS). Most of the methods of this * library are themselves CPS/Node-style async functions, or functions that * return CPS/Node-style async functions. * * Wherever we accept a Node-style async function, we also directly accept an * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. * In this case, the `async` function will not be passed a final callback * argument, and any thrown error will be used as the `err` argument of the * implicit callback, and the return value will be used as the `result` value. * (i.e. a `rejected` of the returned Promise becomes the `err` callback * argument, and a `resolved` value becomes the `result`.) * * Note, due to JavaScript limitations, we can only detect native `async` * functions and not transpilied implementations. * Your environment must have `async`/`await` support for this to work. * (e.g. Node > v7.6, or a recent version of a modern browser). * If you are using `async` functions through a transpiler (e.g. Babel), you * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, * because the `async function` will be compiled to an ordinary function that * returns a promise. * * @typedef {Function} AsyncFunction * @static */ /** * Async is a utility module which provides straight-forward, powerful functions * for working with asynchronous JavaScript. Although originally designed for * use with [Node.js](http://nodejs.org) and installable via * `npm install --save async`, it can also be used directly in the browser. * @module async * @see AsyncFunction */ /** * A collection of `async` functions for manipulating collections, such as * arrays and objects. * @module Collections */ /** * A collection of `async` functions for controlling the flow through a script. * @module ControlFlow */ /** * A collection of `async` utility functions. * @module Utils */ var index = { apply: apply, applyEach: applyEach, applyEachSeries: applyEachSeries, asyncify: asyncify, auto: auto, autoInject: autoInject, cargo: cargo, compose: compose, concat: concat, concatLimit: concatLimit, concatSeries: concatSeries, constant: constant, detect: detect, detectLimit: detectLimit, detectSeries: detectSeries, dir: dir, doDuring: doDuring, doUntil: doUntil, doWhilst: doWhilst, during: during, each: eachLimit, eachLimit: eachLimit$1, eachOf: eachOf, eachOfLimit: eachOfLimit, eachOfSeries: eachOfSeries, eachSeries: eachSeries, ensureAsync: ensureAsync, every: every, everyLimit: everyLimit, everySeries: everySeries, filter: filter, filterLimit: filterLimit, filterSeries: filterSeries, forever: forever, groupBy: groupBy, groupByLimit: groupByLimit, groupBySeries: groupBySeries, log: log, map: map, mapLimit: mapLimit, mapSeries: mapSeries, mapValues: mapValues, mapValuesLimit: mapValuesLimit, mapValuesSeries: mapValuesSeries, memoize: memoize, nextTick: nextTick, parallel: parallelLimit, parallelLimit: parallelLimit$1, priorityQueue: priorityQueue, queue: queue$1, race: race, reduce: reduce, reduceRight: reduceRight, reflect: reflect, reflectAll: reflectAll, reject: reject, rejectLimit: rejectLimit, rejectSeries: rejectSeries, retry: retry, retryable: retryable, seq: seq, series: series, setImmediate: setImmediate$1, some: some, someLimit: someLimit, someSeries: someSeries, sortBy: sortBy, timeout: timeout, times: times, timesLimit: timeLimit, timesSeries: timesSeries, transform: transform, tryEach: tryEach, unmemoize: unmemoize, until: until, waterfall: waterfall, whilst: whilst, // aliases all: every, allLimit: everyLimit, allSeries: everySeries, any: some, anyLimit: someLimit, anySeries: someSeries, find: detect, findLimit: detectLimit, findSeries: detectSeries, forEach: eachLimit, forEachSeries: eachSeries, forEachLimit: eachLimit$1, forEachOf: eachOf, forEachOfSeries: eachOfSeries, forEachOfLimit: eachOfLimit, inject: reduce, foldl: reduce, foldr: reduceRight, select: filter, selectLimit: filterLimit, selectSeries: filterSeries, wrapSync: asyncify }; exports['default'] = index; exports.apply = apply; exports.applyEach = applyEach; exports.applyEachSeries = applyEachSeries; exports.asyncify = asyncify; exports.auto = auto; exports.autoInject = autoInject; exports.cargo = cargo; exports.compose = compose; exports.concat = concat; exports.concatLimit = concatLimit; exports.concatSeries = concatSeries; exports.constant = constant; exports.detect = detect; exports.detectLimit = detectLimit; exports.detectSeries = detectSeries; exports.dir = dir; exports.doDuring = doDuring; exports.doUntil = doUntil; exports.doWhilst = doWhilst; exports.during = during; exports.each = eachLimit; exports.eachLimit = eachLimit$1; exports.eachOf = eachOf; exports.eachOfLimit = eachOfLimit; exports.eachOfSeries = eachOfSeries; exports.eachSeries = eachSeries; exports.ensureAsync = ensureAsync; exports.every = every; exports.everyLimit = everyLimit; exports.everySeries = everySeries; exports.filter = filter; exports.filterLimit = filterLimit; exports.filterSeries = filterSeries; exports.forever = forever; exports.groupBy = groupBy; exports.groupByLimit = groupByLimit; exports.groupBySeries = groupBySeries; exports.log = log; exports.map = map; exports.mapLimit = mapLimit; exports.mapSeries = mapSeries; exports.mapValues = mapValues; exports.mapValuesLimit = mapValuesLimit; exports.mapValuesSeries = mapValuesSeries; exports.memoize = memoize; exports.nextTick = nextTick; exports.parallel = parallelLimit; exports.parallelLimit = parallelLimit$1; exports.priorityQueue = priorityQueue; exports.queue = queue$1; exports.race = race; exports.reduce = reduce; exports.reduceRight = reduceRight; exports.reflect = reflect; exports.reflectAll = reflectAll; exports.reject = reject; exports.rejectLimit = rejectLimit; exports.rejectSeries = rejectSeries; exports.retry = retry; exports.retryable = retryable; exports.seq = seq; exports.series = series; exports.setImmediate = setImmediate$1; exports.some = some; exports.someLimit = someLimit; exports.someSeries = someSeries; exports.sortBy = sortBy; exports.timeout = timeout; exports.times = times; exports.timesLimit = timeLimit; exports.timesSeries = timesSeries; exports.transform = transform; exports.tryEach = tryEach; exports.unmemoize = unmemoize; exports.until = until; exports.waterfall = waterfall; exports.whilst = whilst; exports.all = every; exports.allLimit = everyLimit; exports.allSeries = everySeries; exports.any = some; exports.anyLimit = someLimit; exports.anySeries = someSeries; exports.find = detect; exports.findLimit = detectLimit; exports.findSeries = detectSeries; exports.forEach = eachLimit; exports.forEachSeries = eachSeries; exports.forEachLimit = eachLimit$1; exports.forEachOf = eachOf; exports.forEachOfSeries = eachOfSeries; exports.forEachOfLimit = eachOfLimit; exports.inject = reduce; exports.foldl = reduce; exports.foldr = reduceRight; exports.select = filter; exports.selectLimit = filterLimit; exports.selectSeries = filterSeries; exports.wrapSync = asyncify; Object.defineProperty(exports, '__esModule', { value: true }); })));
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). @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 });
retry ( opts , task , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function autoInject(tasks, callback) { var newTasks = {}; baseForOwn(tasks, function (taskFn, key) { var params; var fnIsAsync = isAsync(taskFn); var hasNoDeps = (!fnIsAsync && taskFn.length === 1) || (fnIsAsync && taskFn.length === 0); if (isArray(taskFn)) { params = taskFn.slice(0, -1); taskFn = taskFn[taskFn.length - 1]; newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); } else if (hasNoDeps) { // no dependencies, use the function as-is newTasks[key] = taskFn; } else { params = parseParams(taskFn); if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { throw new Error("autoInject task functions require explicit parameters."); } // remove callback param if (!fnIsAsync) params.pop(); newTasks[key] = params.concat(newTask); } function newTask(results, taskCb) { var newArgs = arrayMap(params, function (name) { return results[name]; }); newArgs.push(taskCb); wrapAsync(taskFn).apply(null, newArgs); } }); auto(newTasks, callback); } // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation // used for queues. This implementation assumes that the node provided by the user can be modified // to adjust the next and last properties. We implement only the minimal functionality // for queue support. function DLL() { this.head = this.tail = null; this.length = 0; } function setInitial(dll, node) { dll.length = 1; dll.head = dll.tail = node; } DLL.prototype.removeLink = function(node) { if (node.prev) node.prev.next = node.next; else this.head = node.next; if (node.next) node.next.prev = node.prev; else this.tail = node.prev; node.prev = node.next = null; this.length -= 1; return node; }; DLL.prototype.empty = function () { while(this.head) this.shift(); return this; }; DLL.prototype.insertAfter = function(node, newNode) { newNode.prev = node; newNode.next = node.next; if (node.next) node.next.prev = newNode; else this.tail = newNode; node.next = newNode; this.length += 1; }; DLL.prototype.insertBefore = function(node, newNode) { newNode.prev = node.prev; newNode.next = node; if (node.prev) node.prev.next = newNode; else this.head = newNode; node.prev = newNode; this.length += 1; }; DLL.prototype.unshift = function(node) { if (this.head) this.insertBefore(this.head, node); else setInitial(this, node); }; DLL.prototype.push = function(node) { if (this.tail) this.insertAfter(this.tail, node); else setInitial(this, node); }; DLL.prototype.shift = function() { return this.head && this.removeLink(this.head); }; DLL.prototype.pop = function() { return this.tail && this.removeLink(this.tail); }; DLL.prototype.toArray = function () { var arr = Array(this.length); var curr = this.head; for(var idx = 0; idx < this.length; idx++) { arr[idx] = curr.data; curr = curr.next; } return arr; }; DLL.prototype.remove = function (testFn) { var curr = this.head; while(!!curr) { var next = curr.next; if (testFn(curr)) { this.removeLink(curr); } curr = next; } return this; }; function queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } var _worker = wrapAsync(worker); var numRunning = 0; var workersList = []; var processingScheduled = false; function _insert(data, insertAtFront, callback) { if (callback != null && typeof callback !== 'function') { throw new Error('task callback must be a function'); } q.started = true; if (!isArray(data)) { data = [data]; } if (data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return setImmediate$1(function() { q.drain(); }); } for (var i = 0, l = data.length; i < l; i++) { var item = { data: data[i], callback: callback || noop }; if (insertAtFront) { q._tasks.unshift(item); } else { q._tasks.push(item); } } if (!processingScheduled) { processingScheduled = true; setImmediate$1(function() { processingScheduled = false; q.process(); }); } } function _next(tasks) { return function(err){ numRunning -= 1; for (var i = 0, l = tasks.length; i < l; i++) { var task = tasks[i]; var index = baseIndexOf(workersList, task, 0); if (index === 0) { workersList.shift(); } else if (index > 0) { workersList.splice(index, 1); } task.callback.apply(task, arguments); if (err != null) { q.error(err, task.data); } } if (numRunning <= (q.concurrency - q.buffer) ) { q.unsaturated(); } if (q.idle()) { q.drain(); } q.process(); }; } var isProcessing = false; var q = { _tasks: new DLL(), concurrency: concurrency, payload: payload, saturated: noop, unsaturated:noop, buffer: concurrency / 4, empty: noop, drain: noop, error: noop, started: false, paused: false, push: function (data, callback) { _insert(data, false, callback); }, kill: function () { q.drain = noop; q._tasks.empty(); }, unshift: function (data, callback) { _insert(data, true, callback); }, remove: function (testFn) { q._tasks.remove(testFn); }, process: function () { // Avoid trying to start too many processing operations. This can occur // when callbacks resolve synchronously (#1267). if (isProcessing) { return; } isProcessing = true; while(!q.paused && numRunning < q.concurrency && q._tasks.length){ var tasks = [], data = []; var l = q._tasks.length; if (q.payload) l = Math.min(l, q.payload); for (var i = 0; i < l; i++) { var node = q._tasks.shift(); tasks.push(node); workersList.push(node); data.push(node.data); } numRunning += 1; if (q._tasks.length === 0) { q.empty(); } if (numRunning === q.concurrency) { q.saturated(); } var cb = onlyOnce(_next(tasks)); _worker(data, cb); } isProcessing = false; }, length: function () { return q._tasks.length; }, running: function () { return numRunning; }, workersList: function () { return workersList; }, idle: function() { return q._tasks.length + numRunning === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; setImmediate$1(q.process); } }; return q; } /** * A cargo of tasks for the worker function to complete. Cargo inherits all of * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. * @typedef {Object} CargoObject * @memberOf module:ControlFlow * @property {Function} length - A function returning the number of items * waiting to be processed. Invoke like `cargo.length()`. * @property {number} payload - An `integer` for determining how many tasks * should be process per round. This property can be changed after a `cargo` is * created to alter the payload on-the-fly. * @property {Function} push - Adds `task` to the `queue`. The callback is * called once the `worker` has finished processing the task. Instead of a * single task, an array of `tasks` can be submitted. The respective callback is * used for every task in the list. Invoke like `cargo.push(task, [callback])`. * @property {Function} saturated - A callback that is called when the * `queue.length()` hits the concurrency and further tasks will be queued. * @property {Function} empty - A callback that is called when the last item * from the `queue` is given to a `worker`. * @property {Function} drain - A callback that is called when the last item * from the `queue` has returned from the `worker`. * @property {Function} idle - a function returning false if there are items * waiting or being processed, or true if not. Invoke like `cargo.idle()`. * @property {Function} pause - a function that pauses the processing of tasks * until `resume()` is called. Invoke like `cargo.pause()`. * @property {Function} resume - a function that resumes the processing of * queued tasks when the queue is paused. Invoke like `cargo.resume()`. * @property {Function} kill - a function that removes the `drain` callback and * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. */ /** * Creates a `cargo` object with the specified payload. Tasks added to the * cargo will be processed altogether (up to the `payload` limit). If the * `worker` is in progress, the task is queued until it becomes available. Once * the `worker` has completed some tasks, each callback of those tasks is * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) * for how `cargo` and `queue` work. * * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers * at a time, cargo passes an array of tasks to a single worker, repeating * when the worker is finished. * * @name cargo * @static * @memberOf module:ControlFlow * @method * @see [async.queue]{@link module:ControlFlow.queue} * @category Control Flow * @param {AsyncFunction} worker - An asynchronous function for processing an array * of queued tasks. Invoked with `(tasks, callback)`. * @param {number} [payload=Infinity] - An optional `integer` for determining * how many tasks should be processed per round; if omitted, the default is * unlimited. * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can * attached as certain properties to listen for specific events during the * lifecycle of the cargo and inner queue. * @example * * // create a cargo object with payload 2 * var cargo = async.cargo(function(tasks, callback) { * for (var i=0; i<tasks.length; i++) { * console.log('hello ' + tasks[i].name); * } * callback(); * }, 2); * * // add some items * cargo.push({name: 'foo'}, function(err) { * console.log('finished processing foo'); * }); * cargo.push({name: 'bar'}, function(err) { * console.log('finished processing bar'); * }); * cargo.push({name: 'baz'}, function(err) { * console.log('finished processing baz'); * }); */ function cargo(worker, payload) { return queue(worker, 1, payload); } /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. * * @name eachOfSeries * @static * @memberOf module:Collections * @method * @see [async.eachOf]{@link module:Collections.eachOf} * @alias forEachOfSeries * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * Invoked with (item, key, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Invoked with (err). */ var eachOfSeries = doLimit(eachOfLimit, 1); /** * 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|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 complete 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). * @example * * async.reduce([1,2,3], 0, function(memo, item, callback) { * // pointless async: * process.nextTick(function() { * callback(null, memo + item) * }); * }, function(err, result) { * // result is now equal to the last value of memo, which is 6 * }); */ function reduce(coll, memo, iteratee, callback) { callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); eachOfSeries(coll, function(x, i, callback) { _iteratee(memo, x, function(err, v) { memo = v; callback(err); }); }, function(err) { callback(err, memo); }); } /** * 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( * _.bind(User.get, 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 = arrayMap(arguments, wrapAsync); return function(/*...args*/) { var args = slice(arguments); var that = this; var cb = args[args.length - 1]; if (typeof cb == 'function') { args.pop(); } else { cb = noop; } reduce(_functions, args, function(newargs, fn, cb) { fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { var nextargs = slice(arguments, 1); cb(err, nextargs); })); }, function(err, results) { cb.apply(that, [err].concat(results)); }); }; } /** * Creates a function which is a composition of the passed asynchronous * functions. Each function consumes the return value of the function that * follows. Composing functions `f()`, `g()`, and `h()` would produce the result * of `f(g(h()))`, only this version uses callbacks to obtain the return values. * * Each function is executed with the `this` binding of the composed function. * * @name compose * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {...AsyncFunction} functions - the asynchronous functions to compose * @returns {Function} an asynchronous function that is the composed * asynchronous `functions` * @example * * function add1(n, callback) { * setTimeout(function () { * callback(null, n + 1); * }, 10); * } * * function mul3(n, callback) { * setTimeout(function () { * callback(null, n * 3); * }, 10); * } * * var add1mul3 = async.compose(mul3, add1); * add1mul3(4, function (err, result) { * // result now equals 15 * }); */ var compose = function(/*...args*/) { return seq.apply(null, slice(arguments).reverse()); }; var _concat = Array.prototype.concat; /** * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. * * @name concatLimit * @static * @memberOf module:Collections * @method * @see [async.concat]{@link module:Collections.concat} * @category Collection * @param {Array|Iterable|Object} coll - 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 item in `coll`, * which should use an array 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 an array * containing the concatenated results of the `iteratee` function. Invoked with * (err, results). */ var concatLimit = function(coll, limit, iteratee, callback) { callback = callback || noop; var _iteratee = wrapAsync(iteratee); mapLimit(coll, limit, function(val, callback) { _iteratee(val, function(err /*, ...args*/) { if (err) return callback(err); return callback(null, slice(arguments, 1)); }); }, function(err, mapResults) { var result = []; for (var i = 0; i < mapResults.length; i++) { if (mapResults[i]) { result = _concat.apply(result, mapResults[i]); } } return callback(err, result); }); }; /** * Applies `iteratee` to each item in `coll`, concatenating the results. Returns * the concatenated list. The `iteratee`s are called in parallel, and the * results are concatenated as they return. There is no guarantee that the * results array will be returned in the original order of `coll` passed to the * `iteratee` function. * * @name concat * @static * @memberOf module:Collections * @method * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, * which should use an array as its result. Invoked with (item, callback). * @param {Function} [callback(err)] - A callback which is called after all the * `iteratee` functions have finished, or an error occurs. Results is an array * containing the concatenated results of the `iteratee` function. Invoked with * (err, results). * @example * * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { * // files is now a list of filenames that exist in the 3 directories * }); */ var concat = doLimit(concatLimit, Infinity); /** * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. * * @name concatSeries * @static * @memberOf module:Collections * @method * @see [async.concat]{@link module:Collections.concat} * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. * The iteratee should complete with an array an array of results. * Invoked with (item, callback). * @param {Function} [callback(err)] - A callback which is called after all the * `iteratee` functions have finished, or an error occurs. Results is an array * containing the concatenated results of the `iteratee` function. Invoked with * (err, results). */ var concatSeries = doLimit(concatLimit, 1); /** * Returns a function that when called, calls-back with the values provided. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to * [`auto`]{@link module:ControlFlow.auto}. * * @name constant * @static * @memberOf module:Utils * @method * @category Util * @param {...*} arguments... - Any number of arguments to automatically invoke * callback with. * @returns {AsyncFunction} Returns a function that when invoked, automatically * invokes the callback with the previous given arguments. * @example * * async.waterfall([ * async.constant(42), * function (value, next) { * // value === 42 * }, * //... * ], callback); * * async.waterfall([ * async.constant(filename, "utf8"), * fs.readFile, * function (fileData, next) { * //... * } * //... * ], callback); * * async.auto({ * hostname: async.constant("https://server.net/"), * port: findFreePort, * launchServer: ["hostname", "port", function (options, cb) { * startServer(options, cb); * }], * //... * }, callback); */ var constant = function(/*...values*/) { var values = slice(arguments); var args = [null].concat(values); return function (/*...ignoredArgs, callback*/) { var callback = arguments[arguments.length - 1]; return callback.apply(this, args); }; }; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } function _createTester(check, getResult) { return function(eachfn, arr, iteratee, cb) { cb = cb || noop; var testPassed = false; var testResult; eachfn(arr, function(value, _, callback) { iteratee(value, function(err, result) { if (err) { callback(err); } else if (check(result) && !testResult) { testPassed = true; testResult = getResult(true, value); callback(null, breakLoop); } else { callback(); } }); }, function(err) { if (err) { cb(err); } else { cb(null, testPassed ? testResult : getResult(false)); } }); }; } function _findGetResult(v, x) { return x; } /** * Returns the first value in `coll` that passes an async truth test. The * `iteratee` is applied in parallel, meaning the first iteratee to return * `true` will fire the detect `callback` with that result. That means the * result might not be the first item in the original `coll` (in terms of order) * that passes the test. * If order within the original `coll` is important, then look at * [`detectSeries`]{@link module:Collections.detectSeries}. * * @name detect * @static * @memberOf module:Collections * @method * @alias find * @category Collections * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. * The iteratee must complete with a boolean value as its result. * 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 the first item in the array that passes the truth test * (iteratee) or the value `undefined` if none passed. Invoked with * (err, result). * @example * * async.detect(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, result) { * // result now equals the first file in the list that exists * }); */ var detect = doParallel(_createTester(identity, _findGetResult)); /** * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a * time. * * @name detectLimit * @static * @memberOf module:Collections * @method * @see [async.detect]{@link module:Collections.detect} * @alias findLimit * @category Collections * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. * The iteratee must complete with a boolean value as its result. * 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 the first item in the array that passes the truth test * (iteratee) or the value `undefined` if none passed. Invoked with * (err, result). */ var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); /** * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. * * @name detectSeries * @static * @memberOf module:Collections * @method * @see [async.detect]{@link module:Collections.detect} * @alias findSeries * @category Collections * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. * The iteratee must complete with a boolean value as its result. * 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 the first item in the array that passes the truth test * (iteratee) or the value `undefined` if none passed. Invoked with * (err, result). */ var detectSeries = doLimit(detectLimit, 1); function consoleFunc(name) { return function (fn/*, ...args*/) { var args = slice(arguments, 1); args.push(function (err/*, ...args*/) { var args = slice(arguments, 1); if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { arrayEach(args, function (x) { console[name](x); }); } } }); wrapAsync(fn).apply(null, args); }; } /** * Logs the result of an [`async` function]{@link AsyncFunction} to the * `console` using `console.dir` to display the properties of the resulting object. * Only works in Node.js or in browsers that support `console.dir` and * `console.error` (such as FF and Chrome). * If multiple arguments are returned from the async function, * `console.dir` is called on each argument in order. * * @name dir * @static * @memberOf module:Utils * @method * @category Util * @param {AsyncFunction} function - The function you want to eventually apply * all arguments to. * @param {...*} arguments... - Any number of arguments to apply to the function. * @example * * // in a module * var hello = function(name, callback) { * setTimeout(function() { * callback(null, {hello: name}); * }, 1000); * }; * * // in the node repl * node> async.dir(hello, 'world'); * {hello: 'world'} */ var dir = consoleFunc('dir'); /** * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in * the order of operations, the arguments `test` and `fn` are switched. * * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. * @name doDuring * @static * @memberOf module:ControlFlow * @method * @see [async.during]{@link module:ControlFlow.during} * @category Control Flow * @param {AsyncFunction} fn - An async function which is called each time * `test` passes. Invoked with (callback). * @param {AsyncFunction} test - asynchronous truth test to perform before each * execution of `fn`. Invoked with (...args, callback), where `...args` are the * non-error args from the previous callback of `fn`. * @param {Function} [callback] - A callback which is called after the test * function has failed and repeated execution of `fn` has stopped. `callback` * will be passed an error if one occurred, otherwise `null`. */ function doDuring(fn, test, callback) { callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); function next(err/*, ...args*/) { if (err) return callback(err); var args = slice(arguments, 1); args.push(check); _test.apply(this, args); } function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } check(null, true); } /** * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in * the order of operations, the arguments `test` and `iteratee` are switched. * * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. * * @name doWhilst * @static * @memberOf module:ControlFlow * @method * @see [async.whilst]{@link module:ControlFlow.whilst} * @category Control Flow * @param {AsyncFunction} iteratee - A function which is called each time `test` * passes. Invoked with (callback). * @param {Function} test - synchronous truth test to perform after each * execution of `iteratee`. Invoked with any non-error callback results of * `iteratee`. * @param {Function} [callback] - A callback which is called after the test * function has failed 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]); */ function doWhilst(iteratee, test, callback) { callback = onlyOnce(callback || noop); var _iteratee = wrapAsync(iteratee); var next = function(err/*, ...args*/) { if (err) return callback(err); var args = slice(arguments, 1); if (test.apply(this, args)) return _iteratee(next); callback.apply(null, [null].concat(args)); }; _iteratee(next); } /** * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the * argument ordering differs from `until`. * * @name doUntil * @static * @memberOf module:ControlFlow * @method * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} * @category Control Flow * @param {AsyncFunction} iteratee - An async function which is called each time * `test` fails. Invoked with (callback). * @param {Function} test - synchronous truth test to perform after each * execution of `iteratee`. Invoked with any non-error callback results of * `iteratee`. * @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]); */ function doUntil(iteratee, test, callback) { doWhilst(iteratee, function() { return !test.apply(this, arguments); }, callback); } /** * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that * is passed a callback in the form of `function (err, truth)`. If error is * passed to `test` or `fn`, the main callback is immediately called with the * value of the error. * * @name during * @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 `fn`. Invoked with (callback). * @param {AsyncFunction} fn - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test * function has failed and repeated execution of `fn` has stopped. `callback` * will be passed an error, if one occurred, otherwise `null`. * @example * * var count = 0; * * async.during( * function (callback) { * return callback(null, count < 5); * }, * function (callback) { * count++; * setTimeout(callback, 1000); * }, * function (err) { * // 5 seconds have passed * } * ); */ function during(test, fn, callback) { callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); function next(err) { if (err) return callback(err); _test(check); } function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } _test(check); } function _withoutIndex(iteratee) { return function (value, index, callback) { return iteratee(value, callback); }; } /** * Applies the function `iteratee` to each item in `coll`, in parallel. * The `iteratee` is called with an item from the list, and a callback for when * it has finished. If the `iteratee` passes an error to its `callback`, the * main `callback` (for the `each` function) is immediately called with the * error. * * Note, that since this function applies `iteratee` to each item in parallel, * there is no guarantee that the iteratee functions will complete in order. * * @name each * @static * @memberOf module:Collections * @method * @alias forEach * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async function to apply to * each item in `coll`. Invoked with (item, callback). * The array index is not passed to the iteratee. * If you need the index, use `eachOf`. * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @example * * // assuming openFiles is an array of file names and saveFile is a function * // to save the modified contents of that file: * * async.each(openFiles, saveFile, function(err){ * // if any of the saves produced an error, err would equal that error * }); * * // assuming openFiles is an array of file names * async.each(openFiles, function(file, callback) { * * // Perform operation on file here. * console.log('Processing file ' + file); * * if( file.length > 32 ) { * console.log('This file name is too long'); * callback('File name too long'); * } else { * // Do work to process file here * console.log('File processed'); * callback(); * } * }, function(err) { * // if any of the file processing produced an error, err would equal that error * if( err ) { * // One of the iterations produced an error. * // All processing will now stop. * console.log('A file failed to process'); * } else { * console.log('All files have been processed successfully'); * } * }); */ function eachLimit(coll, iteratee, callback) { eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); } /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. * * @name eachLimit * @static * @memberOf module:Collections * @method * @see [async.each]{@link module:Collections.each} * @alias forEachLimit * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The array index is not passed to the iteratee. * If you need the index, use `eachOfLimit`. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ function eachLimit$1(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } /** * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. * * @name eachSeries * @static * @memberOf module:Collections * @method * @see [async.each]{@link module:Collections.each} * @alias forEachSeries * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async function to apply to each * item in `coll`. * The array index is not passed to the iteratee. * If you need the index, use `eachOfSeries`. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ var eachSeries = doLimit(eachLimit$1, 1); /** * Wrap an async function and ensure it calls its callback on a later tick of * the event loop. If the function already calls its callback on a next tick, * no extra deferral is added. This is useful for preventing stack overflows * (`RangeError: Maximum call stack size exceeded`) and generally keeping * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) * contained. ES2017 `async` functions are returned as-is -- they are immune * to Zalgo's corrupting influences, as they always resolve on a later tick. * * @name ensureAsync * @static * @memberOf module:Utils * @method * @category Util * @param {AsyncFunction} fn - an async function, one that expects a node-style * callback as its last argument. * @returns {AsyncFunction} Returns a wrapped function with the exact same call * signature as the function passed in. * @example * * function sometimesAsync(arg, callback) { * if (cache[arg]) { * return callback(null, cache[arg]); // this would be synchronous!! * } else { * doSomeIO(arg, callback); // this IO would be asynchronous * } * } * * // this has a risk of stack overflows if many results are cached in a row * async.mapSeries(args, sometimesAsync, done); * * // this will defer sometimesAsync's callback if necessary, * // preventing stack overflows * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); */ function ensureAsync(fn) { if (isAsync(fn)) return fn; return initialParams(function (args, callback) { var sync = true; args.push(function () { var innerArgs = arguments; if (sync) { setImmediate$1(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); fn.apply(this, args); sync = false; }); } function notId(v) { return !v; } /** * Returns `true` if every element in `coll` satisfies an async test. If any * iteratee call returns `false`, the main `callback` is immediately called. * * @name every * @static * @memberOf module:Collections * @method * @alias all * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async truth test to apply to each item * in the collection in parallel. * The iteratee must complete with a boolean result value. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called 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). * @example * * async.every(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, result) { * // if result is true then every file exists * }); */ var every = doParallel(_createTester(notId, notId)); /** * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. * * @name everyLimit * @static * @memberOf module:Collections * @method * @see [async.every]{@link module:Collections.every} * @alias allLimit * @category Collection * @param {Array|Iterable|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 collection in parallel. * The iteratee must complete with a boolean result value. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called 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). */ var everyLimit = doParallelLimit(_createTester(notId, notId)); /** * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. * * @name everySeries * @static * @memberOf module:Collections * @method * @see [async.every]{@link module:Collections.every} * @alias allSeries * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async truth test to apply to each item * in the collection in series. * The iteratee must complete with a boolean result value. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called 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). */ var everySeries = doLimit(everyLimit, 1); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } function filterArray(eachfn, arr, iteratee, callback) { var truthValues = new Array(arr.length); eachfn(arr, function (x, index, callback) { iteratee(x, function (err, v) { truthValues[index] = !!v; callback(err); }); }, function (err) { if (err) return callback(err); var results = []; for (var i = 0; i < arr.length; i++) { if (truthValues[i]) results.push(arr[i]); } callback(null, results); }); } function filterGeneric(eachfn, coll, iteratee, callback) { var results = []; eachfn(coll, function (x, index, callback) { iteratee(x, function (err, v) { if (err) { callback(err); } else { if (v) { results.push({index: index, value: x}); } callback(); } }); }, function (err) { if (err) { callback(err); } else { callback(null, arrayMap(results.sort(function (a, b) { return a.index - b.index; }), baseProperty('value'))); } }); } function _filter(eachfn, coll, iteratee, callback) { var filter = isArrayLike(coll) ? filterArray : filterGeneric; filter(eachfn, coll, wrapAsync(iteratee), callback || noop); } /** * 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|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). * @example * * async.filter(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, results) { * // results now equals an array of the existing files * }); */ var filter = doParallel(_filter); /** * 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|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). */ var filterLimit = doParallelLimit(_filter); /** * 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|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) */ var filterSeries = doLimit(filterLimit, 1); /** * Calls the asynchronous function `fn` with a callback parameter that allows it * to call itself again, in series, indefinitely. * If an error is passed to the callback then `errback` is called with the * error, and execution stops, otherwise it will never be called. * * @name forever * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {AsyncFunction} fn - an async function to call repeatedly. * Invoked with (next). * @param {Function} [errback] - when `fn` passes an error to it's callback, * this function will be called, and execution stops. Invoked with (err). * @example * * async.forever( * function(next) { * // next is suitable for passing to things that need a callback(err [, whatever]); * // it will result in this function being called again. * }, * function(err) { * // if next is called with a value in its first parameter, it will appear * // in here as 'err', and execution will stop. * } * ); */ function forever(fn, errback) { var done = onlyOnce(errback || noop); var task = wrapAsync(ensureAsync(fn)); function next(err) { if (err) return done(err); task(next); } next(); } /** * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. * * @name groupByLimit * @static * @memberOf module:Collections * @method * @see [async.groupBy]{@link module:Collections.groupBy} * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The iteratee should complete with a `key` to group the value under. * Invoked with (value, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Result is an `Object` whoses * properties are arrays of values which returned the corresponding key. */ var groupByLimit = function(coll, limit, iteratee, callback) { callback = callback || noop; var _iteratee = wrapAsync(iteratee); mapLimit(coll, limit, function(val, callback) { _iteratee(val, function(err, key) { if (err) return callback(err); return callback(null, {key: key, val: val}); }); }, function(err, mapResults) { var result = {}; // from MDN, handle object having an `hasOwnProperty` prop var hasOwnProperty = Object.prototype.hasOwnProperty; for (var i = 0; i < mapResults.length; i++) { if (mapResults[i]) { var key = mapResults[i].key; var val = mapResults[i].val; if (hasOwnProperty.call(result, key)) { result[key].push(val); } else { result[key] = [val]; } } } return callback(err, result); }); }; /** * Returns a new object, where each value corresponds to an array of items, from * `coll`, that returned the corresponding key. That is, the keys of the object * correspond to the values passed to the `iteratee` callback. * * Note: Since this function applies the `iteratee` to each item in parallel, * there is no guarantee that the `iteratee` functions will complete in order. * However, the values for each key in the `result` will be in the same order as * the original `coll`. For Objects, the values will roughly be in the order of * the original Objects' keys (but this can vary across JavaScript engines). * * @name groupBy * @static * @memberOf module:Collections * @method * @category Collection * @param {Array|Iterable|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 `key` to group the value under. * Invoked with (value, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Result is an `Object` whoses * properties are arrays of values which returned the corresponding key. * @example * * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { * db.findById(userId, function(err, user) { * if (err) return callback(err); * return callback(null, user.age); * }); * }, function(err, result) { * // result is object containing the userIds grouped by age * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; * }); */ var groupBy = doLimit(groupByLimit, Infinity); /** * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. * * @name groupBySeries * @static * @memberOf module:Collections * @method * @see [async.groupBy]{@link module:Collections.groupBy} * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The iteratee should complete with a `key` to group the value under. * Invoked with (value, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Result is an `Object` whoses * properties are arrays of values which returned the corresponding key. */ var groupBySeries = doLimit(groupByLimit, 1); /** * Logs the result of an `async` function to the `console`. Only works in * Node.js or in browsers that support `console.log` and `console.error` (such * as FF and Chrome). If multiple arguments are returned from the async * function, `console.log` is called on each argument in order. * * @name log * @static * @memberOf module:Utils * @method * @category Util * @param {AsyncFunction} function - The function you want to eventually apply * all arguments to. * @param {...*} arguments... - Any number of arguments to apply to the function. * @example * * // in a module * var hello = function(name, callback) { * setTimeout(function() { * callback(null, 'hello ' + name); * }, 1000); * }; * * // in the node repl * node> async.log(hello, 'world'); * 'hello world' */ var log = consoleFunc('log'); /** * 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). */ function mapValuesLimit(obj, limit, iteratee, callback) { callback = once(callback || noop); var newObj = {}; var _iteratee = wrapAsync(iteratee); eachOfLimit(obj, limit, function(val, key, next) { _iteratee(val, key, function (err, result) { if (err) return next(err); newObj[key] = result; next(); }); }, function (err) { callback(err, newObj); }); } /** * 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). * @example * * async.mapValues({ * f1: 'file1', * f2: 'file2', * f3: 'file3' * }, function (file, key, callback) { * fs.stat(file, callback); * }, function(err, result) { * // result is now a map of stats for each file, e.g. * // { * // f1: [stats for file1], * // f2: [stats for file2], * // f3: [stats for file3] * // } * }); */ var mapValues = doLimit(mapValuesLimit, Infinity); /** * 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). */ var mapValuesSeries = doLimit(mapValuesLimit, 1); function has(obj, key) { return key in 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. * * 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) { var memo = Object.create(null); var queues = Object.create(null); hasher = hasher || identity; var _fn = wrapAsync(fn); var memoized = initialParams(function memoized(args, callback) { var key = hasher.apply(null, args); if (has(memo, key)) { setImmediate$1(function() { callback.apply(null, memo[key]); }); } else if (has(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; _fn.apply(null, args.concat(function(/*args*/) { var args = slice(arguments); memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; } /** * Calls `callback` on a later loop around the event loop. In Node.js this just * calls `process.nextTicl`. 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$1; if (hasNextTick) { _defer$1 = process.nextTick; } else if (hasSetImmediate) { _defer$1 = setImmediate; } else { _defer$1 = fallback; } var nextTick = wrap(_defer$1); function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { wrapAsync(task)(function (err, result) { if (arguments.length > 2) { result = slice(arguments, 1); } results[key] = result; callback(err); }); }, function (err) { callback(err, results); }); } /** * 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|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). * * @example * async.parallel([ * function(callback) { * setTimeout(function() { * callback(null, 'one'); * }, 200); * }, * function(callback) { * setTimeout(function() { * callback(null, 'two'); * }, 100); * } * ], * // optional callback * function(err, results) { * // the results array will equal ['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) { * // results is now equals to: {one: 1, two: 2} * }); */ function parallelLimit(tasks, callback) { _parallel(eachOf, tasks, callback); } /** * 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|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). */ function parallelLimit$1(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); } /** * A queue of tasks for the worker function to complete. * @typedef {Object} 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 {Function} 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 {Function} unshift - add a new task to the front of the `queue`. * Invoke with `queue.unshift(task, [callback])`. * @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 callback that is called when the number of * running workers hits the `concurrency` limit, and further tasks will be * queued. * @property {Function} unsaturated - 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. * @property {number} buffer - A minimum threshold buffer in order to say that * the `queue` is `unsaturated`. * @property {Function} empty - a callback that is called when the last item * from the `queue` is given to a `worker`. * @property {Function} drain - a callback that is called when the last item * from the `queue` has returned from the `worker`. * @property {Function} error - a callback that is called when a task errors. * Has the signature `function(error, task)`. * @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()`. */ /** * 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 * 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'); * }; * * // add some items to the queue * q.push({name: 'foo'}, function(err) { * console.log('finished processing foo'); * }); * q.push({name: 'bar'}, function (err) { * console.log('finished processing 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'); * }); */ var queue$1 = function (worker, concurrency) { var _worker = wrapAsync(worker); return queue(function (items, cb) { _worker(items[0], cb); }, concurrency, 1); }; /** * 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 two * 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. * * The `unshift` method was removed. */ var priorityQueue = function(worker, concurrency) { // Start with a normal queue var q = queue$1(worker, concurrency); // Override push to accept second parameter representing priority q.push = function(data, priority, callback) { if (callback == null) callback = noop; if (typeof callback !== 'function') { throw new Error('task callback must be a function'); } q.started = true; if (!isArray(data)) { data = [data]; } if (data.length === 0) { // call drain immediately if there are no tasks return setImmediate$1(function() { q.drain(); }); } priority = priority || 0; var nextNode = q._tasks.head; while (nextNode && priority >= nextNode.priority) { nextNode = nextNode.next; } for (var i = 0, l = data.length; i < l; i++) { var item = { data: data[i], priority: priority, callback: callback }; if (nextNode) { q._tasks.insertBefore(nextNode, item); } else { q._tasks.push(item); } } setImmediate$1(q.process); }; // Remove unshift function delete q.unshift; return q; }; /** * 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 undefined * @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 = once(callback || noop); if (!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++) { wrapAsync(tasks[i])(callback); } } /** * 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 complete 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). */ function reduceRight (array, memo, iteratee, callback) { var reversed = slice(array).reverse(); reduce(reversed, memo, iteratee, callback); } /** * 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 = wrapAsync(fn); return initialParams(function reflectOn(args, reflectCallback) { args.push(function callback(error, cbArg) { if (error) { reflectCallback(null, { error: error }); } else { var value; if (arguments.length <= 2) { value = cbArg; } else { value = slice(arguments, 1); } reflectCallback(null, { value: value }); } }); return _fn.apply(this, args); }); } /** * 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 (isArray(tasks)) { results = arrayMap(tasks, reflect); } else { results = {}; baseForOwn(tasks, function(task, key) { results[key] = reflect.call(this, task); }); } return results; } function reject$1(eachfn, arr, iteratee, callback) { _filter(eachfn, arr, function(value, cb) { iteratee(value, function(err, v) { cb(err, !v); }); }, callback); } /** * 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|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). * @example * * async.reject(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, results) { * // results now equals an array of missing files * createFiles(results); * }); */ var reject = doParallel(reject$1); /** * 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|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). */ var rejectLimit = doParallelLimit(reject$1); /** * 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|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). */ var rejectSeries = doLimit(rejectLimit, 1); /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant$1(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). * * @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 * }); * */ function retry(opts, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var options = { times: DEFAULT_TIMES, intervalFunc: constant$1(DEFAULT_INTERVAL) }; function parseTimes(acc, t) { if (typeof t === 'object') { acc.times = +t.times || DEFAULT_TIMES; acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+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"); } } if (arguments.length < 3 && typeof opts === 'function') { callback = task || noop; task = opts; } else { parseTimes(options, opts); callback = callback || noop; } if (typeof task !== 'function') { throw new Error("Invalid arguments for async.retry"); } var _task = wrapAsync(task); var attempt = 1; function retryAttempt() { _task(function(err) { if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { setTimeout(retryAttempt, options.intervalFunc(attempt)); } else { callback.apply(null, arguments); } }); } retryAttempt(); } /** * 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` * @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); */ var retryable = function (opts, task) { if (!task) { task = opts; opts = null; } var _task = wrapAsync(task); return initialParams(function (args, callback) { function taskFn(cb) { _task.apply(null, args.concat(cb)); } if (opts) retry(opts, taskFn, callback); else retry(taskFn, callback); }); }; /** * 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|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). * @example * async.series([ * function(callback) { * // do some stuff ... * callback(null, 'one'); * }, * function(callback) { * // do some more stuff ... * callback(null, 'two'); * } * ], * // optional callback * function(err, results) { * // results is now equal to ['one', 'two'] * }); * * async.series({ * one: function(callback) { * setTimeout(function() { * callback(null, 1); * }, 200); * }, * two: function(callback){ * setTimeout(function() { * callback(null, 2); * }, 100); * } * }, function(err, results) { * // results is now equal to: {one: 1, two: 2} * }); */ function series(tasks, callback) { _parallel(eachOfSeries, tasks, callback); } /** * 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|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). * @example * * async.some(['file1','file2','file3'], function(filePath, callback) { * fs.access(filePath, function(err) { * callback(null, !err) * }); * }, function(err, result) { * // if result is true then at least one of the files exists * }); */ var some = doParallel(_createTester(Boolean, identity)); /** * 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|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). */ var someLimit = doParallelLimit(_createTester(Boolean, identity)); /** * 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|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). */ var someSeries = doLimit(someLimit, 1); /** * 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|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). * @example * * async.sortBy(['file1','file2','file3'], function(file, callback) { * fs.stat(file, function(err, stats) { * callback(err, stats.mtime); * }); * }, function(err, results) { * // results is now the original array of files sorted by * // modified date * }); * * // By modifying the callback parameter the * // sorting order can be influenced: * * // ascending order * async.sortBy([1,9,3,5], function(x, callback) { * callback(null, x); * }, function(err,result) { * // result callback * }); * * // descending order * async.sortBy([1,9,3,5], function(x, callback) { * callback(null, x*-1); //<- x*-1 instead of x, turns the order around * }, function(err,result) { * // result callback * }); */ function sortBy (coll, iteratee, callback) { var _iteratee = wrapAsync(iteratee); map(coll, function (x, callback) { _iteratee(x, function (err, criteria) { if (err) return callback(err); callback(null, {value: x, criteria: criteria}); }); }, function (err, results) { if (err) return callback(err); callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } } /** * 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 = wrapAsync(asyncFn); return initialParams(function (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(function () { if (!timedOut) { callback.apply(null, arguments); clearTimeout(timer); } }); // setup timer and call original function timer = setTimeout(timeoutCallback, milliseconds); fn.apply(null, args); }); } /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; var nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * 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}. */ function timeLimit(count, limit, iteratee, callback) { var _iteratee = wrapAsync(iteratee); mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); } /** * 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}. * @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 * }); */ var times = doLimit(timeLimit, Infinity); /** * 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}. */ var timesSeries = doLimit(timeLimit, 1); /** * A relative of `reduce`. Takes an Object or Array, and iterates over each * element in series, 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|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). * @example * * async.transform([1,2,3], function(acc, item, index, callback) { * // pointless async: * process.nextTick(function() { * acc.push(item * 2) * callback(null) * }); * }, function(err, result) { * // result is now equal to [2, 4, 6] * }); * * @example * * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { * setImmediate(function () { * obj[key] = val * 2; * callback(); * }) * }, function (err, result) { * // result is equal to {a: 2, b: 4, c: 6} * }) */ function transform (coll, accumulator, iteratee, callback) { if (arguments.length <= 3) { callback = iteratee; iteratee = accumulator; accumulator = isArray(coll) ? [] : {}; } callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); eachOf(coll, function(v, k, cb) { _iteratee(accumulator, v, k, cb); }, function(err) { callback(err, accumulator); }); } /** * It runs each task in series but stops whenever any of the functions were * successful. If one of the tasks were successful, the `callback` will be * passed the result of the successful task. If all tasks fail, the callback * will be passed the error and result (if any) of the final attempt. * * @name tryEach * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Array|Iterable|Object} tasks - A collection containing functions to * run, each function is passed a `callback(err, result)` it must call on * completion with an error `err` (which can be `null`) and an optional `result` * value. * @param {Function} [callback] - An optional callback which is called when one * of the tasks has succeeded, or all have failed. It receives the `err` and * `result` arguments of the last attempt at completing the `task`. Invoked with * (err, results). * @example * async.tryEach([ * function getDataFromFirstWebsite(callback) { * // Try getting the data from the first website * callback(err, data); * }, * function getDataFromSecondWebsite(callback) { * // First website failed, * // Try getting the data from the backup website * callback(err, data); * } * ], * // optional callback * function(err, results) { * Now do something with the data. * }); * */ function tryEach(tasks, callback) { var error = null; var result; callback = callback || noop; eachSeries(tasks, function(task, callback) { wrapAsync(task)(function (err, res/*, ...args*/) { if (arguments.length > 2) { result = slice(arguments, 1); } else { result = res; } error = err; callback(!err); }); }, function () { callback(error, result); }); } /** * 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 function () { return (fn.unmemoized || fn).apply(null, arguments); }; } /** * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when * stopped, or an error occurs. * * @name whilst * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Function} test - synchronous truth test to perform before each * execution of `iteratee`. Invoked with (). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test * function has failed 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 undefined * @example * * var count = 0; * async.whilst( * function() { return count < 5; }, * function(callback) { * count++; * setTimeout(function() { * callback(null, count); * }, 1000); * }, * function (err, n) { * // 5 seconds have passed, n = 5 * } * ); */ function whilst(test, iteratee, callback) { callback = onlyOnce(callback || noop); var _iteratee = wrapAsync(iteratee); if (!test()) return callback(null); var next = function(err/*, ...args*/) { if (err) return callback(err); if (test()) return _iteratee(next); var args = slice(arguments, 1); callback.apply(null, [null].concat(args)); }; _iteratee(next); } /** * 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 {Function} test - synchronous truth test to perform before each * execution of `iteratee`. Invoked with (). * @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]); */ function until(test, iteratee, callback) { whilst(function() { return !test.apply(this, arguments); }, iteratee, callback); } /** * 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 undefined * @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'); * } */ var waterfall = function(tasks, callback) { callback = once(callback || noop); if (!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 = wrapAsync(tasks[taskIndex++]); args.push(onlyOnce(next)); task.apply(null, args); } function next(err/*, ...args*/) { if (err || taskIndex === tasks.length) { return callback.apply(null, arguments); } nextTask(slice(arguments, 1)); } nextTask([]); }; /** * An "async function" in the context of Async is an asynchronous function with * a variable number of parameters, with the final parameter being a callback. * (`function (arg1, arg2, ..., callback) {}`) * The final callback is of the form `callback(err, results...)`, which must be * called once the function is completed. The callback should be called with a * Error as its first argument to signal that an error occurred. * Otherwise, if no error occurred, it should be called with `null` as the first * argument, and any additional `result` arguments that may apply, to signal * successful completion. * The callback must be called exactly once, ideally on a later tick of the * JavaScript event loop. * * This type of function is also referred to as a "Node-style async function", * or a "continuation passing-style function" (CPS). Most of the methods of this * library are themselves CPS/Node-style async functions, or functions that * return CPS/Node-style async functions. * * Wherever we accept a Node-style async function, we also directly accept an * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. * In this case, the `async` function will not be passed a final callback * argument, and any thrown error will be used as the `err` argument of the * implicit callback, and the return value will be used as the `result` value. * (i.e. a `rejected` of the returned Promise becomes the `err` callback * argument, and a `resolved` value becomes the `result`.) * * Note, due to JavaScript limitations, we can only detect native `async` * functions and not transpilied implementations. * Your environment must have `async`/`await` support for this to work. * (e.g. Node > v7.6, or a recent version of a modern browser). * If you are using `async` functions through a transpiler (e.g. Babel), you * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, * because the `async function` will be compiled to an ordinary function that * returns a promise. * * @typedef {Function} AsyncFunction * @static */ /** * Async is a utility module which provides straight-forward, powerful functions * for working with asynchronous JavaScript. Although originally designed for * use with [Node.js](http://nodejs.org) and installable via * `npm install --save async`, it can also be used directly in the browser. * @module async * @see AsyncFunction */ /** * A collection of `async` functions for manipulating collections, such as * arrays and objects. * @module Collections */ /** * A collection of `async` functions for controlling the flow through a script. * @module ControlFlow */ /** * A collection of `async` utility functions. * @module Utils */ var index = { apply: apply, applyEach: applyEach, applyEachSeries: applyEachSeries, asyncify: asyncify, auto: auto, autoInject: autoInject, cargo: cargo, compose: compose, concat: concat, concatLimit: concatLimit, concatSeries: concatSeries, constant: constant, detect: detect, detectLimit: detectLimit, detectSeries: detectSeries, dir: dir, doDuring: doDuring, doUntil: doUntil, doWhilst: doWhilst, during: during, each: eachLimit, eachLimit: eachLimit$1, eachOf: eachOf, eachOfLimit: eachOfLimit, eachOfSeries: eachOfSeries, eachSeries: eachSeries, ensureAsync: ensureAsync, every: every, everyLimit: everyLimit, everySeries: everySeries, filter: filter, filterLimit: filterLimit, filterSeries: filterSeries, forever: forever, groupBy: groupBy, groupByLimit: groupByLimit, groupBySeries: groupBySeries, log: log, map: map, mapLimit: mapLimit, mapSeries: mapSeries, mapValues: mapValues, mapValuesLimit: mapValuesLimit, mapValuesSeries: mapValuesSeries, memoize: memoize, nextTick: nextTick, parallel: parallelLimit, parallelLimit: parallelLimit$1, priorityQueue: priorityQueue, queue: queue$1, race: race, reduce: reduce, reduceRight: reduceRight, reflect: reflect, reflectAll: reflectAll, reject: reject, rejectLimit: rejectLimit, rejectSeries: rejectSeries, retry: retry, retryable: retryable, seq: seq, series: series, setImmediate: setImmediate$1, some: some, someLimit: someLimit, someSeries: someSeries, sortBy: sortBy, timeout: timeout, times: times, timesLimit: timeLimit, timesSeries: timesSeries, transform: transform, tryEach: tryEach, unmemoize: unmemoize, until: until, waterfall: waterfall, whilst: whilst, // aliases all: every, allLimit: everyLimit, allSeries: everySeries, any: some, anyLimit: someLimit, anySeries: someSeries, find: detect, findLimit: detectLimit, findSeries: detectSeries, forEach: eachLimit, forEachSeries: eachSeries, forEachLimit: eachLimit$1, forEachOf: eachOf, forEachOfSeries: eachOfSeries, forEachOfLimit: eachOfLimit, inject: reduce, foldl: reduce, foldr: reduceRight, select: filter, selectLimit: filterLimit, selectSeries: filterSeries, wrapSync: asyncify }; exports['default'] = index; exports.apply = apply; exports.applyEach = applyEach; exports.applyEachSeries = applyEachSeries; exports.asyncify = asyncify; exports.auto = auto; exports.autoInject = autoInject; exports.cargo = cargo; exports.compose = compose; exports.concat = concat; exports.concatLimit = concatLimit; exports.concatSeries = concatSeries; exports.constant = constant; exports.detect = detect; exports.detectLimit = detectLimit; exports.detectSeries = detectSeries; exports.dir = dir; exports.doDuring = doDuring; exports.doUntil = doUntil; exports.doWhilst = doWhilst; exports.during = during; exports.each = eachLimit; exports.eachLimit = eachLimit$1; exports.eachOf = eachOf; exports.eachOfLimit = eachOfLimit; exports.eachOfSeries = eachOfSeries; exports.eachSeries = eachSeries; exports.ensureAsync = ensureAsync; exports.every = every; exports.everyLimit = everyLimit; exports.everySeries = everySeries; exports.filter = filter; exports.filterLimit = filterLimit; exports.filterSeries = filterSeries; exports.forever = forever; exports.groupBy = groupBy; exports.groupByLimit = groupByLimit; exports.groupBySeries = groupBySeries; exports.log = log; exports.map = map; exports.mapLimit = mapLimit; exports.mapSeries = mapSeries; exports.mapValues = mapValues; exports.mapValuesLimit = mapValuesLimit; exports.mapValuesSeries = mapValuesSeries; exports.memoize = memoize; exports.nextTick = nextTick; exports.parallel = parallelLimit; exports.parallelLimit = parallelLimit$1; exports.priorityQueue = priorityQueue; exports.queue = queue$1; exports.race = race; exports.reduce = reduce; exports.reduceRight = reduceRight; exports.reflect = reflect; exports.reflectAll = reflectAll; exports.reject = reject; exports.rejectLimit = rejectLimit; exports.rejectSeries = rejectSeries; exports.retry = retry; exports.retryable = retryable; exports.seq = seq; exports.series = series; exports.setImmediate = setImmediate$1; exports.some = some; exports.someLimit = someLimit; exports.someSeries = someSeries; exports.sortBy = sortBy; exports.timeout = timeout; exports.times = times; exports.timesLimit = timeLimit; exports.timesSeries = timesSeries; exports.transform = transform; exports.tryEach = tryEach; exports.unmemoize = unmemoize; exports.until = until; exports.waterfall = waterfall; exports.whilst = whilst; exports.all = every; exports.allLimit = everyLimit; exports.allSeries = everySeries; exports.any = some; exports.anyLimit = someLimit; exports.anySeries = someSeries; exports.find = detect; exports.findLimit = detectLimit; exports.findSeries = detectSeries; exports.forEach = eachLimit; exports.forEachSeries = eachSeries; exports.forEachLimit = eachLimit$1; exports.forEachOf = eachOf; exports.forEachOfSeries = eachOfSeries; exports.forEachOfLimit = eachOfLimit; exports.inject = reduce; exports.foldl = reduce; exports.foldr = reduceRight; exports.select = filter; exports.selectLimit = filterLimit; exports.selectSeries = filterSeries; exports.wrapSync = asyncify; Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent tasks are specified as parameters to the function, after the usual callback parameter, with the parameter names matching the names of the tasks it depends on. This can provide even more readable task graphs which can be easier to maintain. If a final callback is specified, the task results are similarly injected, specified as named parameters after the initial error parameter. The autoInject function is purely syntactic sugar and its semantics are otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. @name autoInject @static @memberOf module:ControlFlow @method @see [async.auto]{@link module:ControlFlow.auto} @category Control Flow @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of the form 'func([dependencies...], callback). The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks. * The `callback` parameter is a `callback(err, result)` which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution. The remaining parameters name other tasks on which the task is dependent, and the results from those tasks are the arguments of those parameters. @param {Function} [callback] - An optional callback which is called when all the tasks have been completed. It receives the `err` argument if any `tasks` pass an error to their callback, and a `results` object with any completed task results, similar to `auto`. @example // The example from `auto` can be rewritten as follows: async.autoInject({ get_data: function(callback) { // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback) { // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, write_file: function(get_data, make_folder, callback) { // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }, email_link: function(write_file, callback) { // once the file is written let's email a link to it... // write_file contains the filename returned by write_file. callback(null, {'file':write_file, 'email':'[email protected]'}); } }, function(err, results) { console.log('err = ', err); console.log('email_link = ', results.email_link); }); // If you are using a JS minifier that mangles parameter names, `autoInject` // will not work with plain functions, since the parameter names will be // collapsed to a single letter identifier. To work around this, you can // explicitly specify the names of the parameters your task function needs // in an array, similar to Angular.js dependency injection. // This still has an advantage over plain `auto`, since the results a task // depends on are still spread into arguments. async.autoInject({ //... write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { callback(null, 'filename'); }], email_link: ['write_file', function(write_file, callback) { callback(null, {'file':write_file, 'email':'[email protected]'}); }] //... }, function(err, results) { console.log('err = ', err); console.log('email_link = ', results.email_link); });
autoInject ( tasks , callback )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) }
The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified.
Buffer ( arg , encodingOrOffset , length )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0
Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) }
Functionally equivalent to Buffer(arg, encoding) but throws a TypeError if value is a number. Buffer.from(str[, encoding]) Buffer.from(array) Buffer.from(buffer) Buffer.from(arrayBuffer[, byteOffset[, length]]) *
Buffer.from ( value , encodingOrOffset , length )
javascript
web3swift-team/web3swift
Sources/web3swift/Browser/browser.js
https://github.com/web3swift-team/web3swift/blob/master/Sources/web3swift/Browser/browser.js
Apache-2.0