Skip to content

ym.Async Methods

map(list, iterator, completeopt, asyncFnopt, contextopt) ab v3

The map function is a wrapper component that controls the behavior of an asynchronous mapping. You can create your own asynchronous control function or let mapSeries and mapParallel do the job.

Parameters

  • list
    Data type: array

  • iterator
    Data type: function

  • completeopt
    Data type: function or null
    Default value: null

  • asyncFnopt
    Data type: function
    Default value: ym.async.parallel

  • contextopt
    Data type: object or null
    Default value: null

Example Call

// the iterator is a function with the current item of the array and a
// callback. At the end of an asynchronous call the done() callback must
// be triggered to end the process.
function iterator(item, done) {
    // this is a simple echo script. It will answer in a time period
    // between 0 and 500 milliseconds.
    setTimeout(function () {
        console.log(item);
        done(null, item);
    }, Math.random() * 500);
}

// The complete callback will be triggered after any array element is executed.
function complete(err, results) {
    console.log("done!", err, results);
}

// your customized asynchronous iteration control.
function asyncFn(queue, complete, context) {
    var fn;
    var results = [];
    var len = queue.length;

    // the callback will be executed in the iterator after the asynchronous command is finished.
    // It is decrementing the length of the queue until every asynchronous command is complete.
    function next(err, data) {
        results.push(data);
        if (!--len || err) {
            complete.call(context || complete, err, results);
        }
    }

    // the main loop is done very quickly. It is a parallel loop.
    while (fn = queue.pop()) {
        fn.call(context || {}, next);
    }

    // an empty array causes the execution of the complete callback
    // instantly
    if (!len) {
        complete.call(context || complete, null, results);
    }
}

// the function call for the map function
ym.async.map(["a", "b", "c"], iterator, complete, asyncFn);