Related Tags

async
javascript

How to use constant() in Async

constant() in the Async module is a method that returns a function that, when used, automatically invokes the callback with the given arguments.

constant() is useful as the first function in a waterfall or for plugging values into auto.

Syntax

constant(arguments...)

• arguments: Any number of arguments to automatically invoke the callback with. It is usually a constant value.

The callback returns a function that, when called, calls-back with the provided values. In other words, it returns the values provided to it so that those values can be used by the call-back (next function).

Example

A common use case for constant() is to pass arguments to the first function in waterfall. constant() is the first function to accomplish that. The arguments you pass to the constant() are then used as arguments to invoke the callback (the next function).

In the code below, we have a waterfall. Notice that the function after the constant() function is invoked with the value $42$.

import waterfall from 'async/waterfall';
import constant from 'async/constant';

waterfall([
constant(42),
function (value, next) {
// value === 42
console.log(value);
},
//...

], function(err, result){
// final callback of waterfall
// ...
});

You can read more about waterfall here.

RELATED TAGS

async
javascript