Zum Inhalt

ym.Async-Methoden

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

Die Funktion map ist eine Wrapper-Komponente, die das Verhalten eines asynchronen Mappings steuert. Sie können Ihre eigene asynchrone Steuerungsfunktion erstellen oder mapSeries und mapParallel diese Aufgabe übernehmen lassen.

Parameter

  • list
    Datentyp: array

  • iterator
    Datentyp: function

  • completeopt
    Datentyp: function or null
    Standardwert: null

  • asyncFnopt
    Datentyp: function
    Standardwert: ym.async.parallel

  • contextopt
    Datentyp: object or null
    Standardwert: null

Beispielaufruf

// 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);