import noop from 'lodash/noop';
import onlyOnce from './internal/onlyOnce';
import ensureAsync from './ensureAsync';
import wrapAsync from './internal/wrapAsync';
/**
* 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.
* }
* );
*/
export default 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();
}