Whats the smartest / cleanest way to iterate async over arrays (or objs)?

后端 未结 4 1252
礼貌的吻别
礼貌的吻别 2020-12-01 04:45

Thats how I do it:

function processArray(array, index, callback) {
    processItem(array[index], function(){
        if(++index === array.length) {
                  


        
4条回答
  •  無奈伤痛
    2020-12-01 04:59

    As pointed in some answer one can use "async" library. But sometimes you just don't want to introduce new dependency in your code. And below is another way how you can loop and wait for completion of some asynchronous functions.

    var items = ["one", "two", "three"];
    
    // This is your async function, which may perform call to your database or
    // whatever...
    function someAsyncFunc(arg, cb) {
        setTimeout(function () {
            cb(arg.toUpperCase());
        }, 3000);
    }
    
    // cb will be called when each item from arr has been processed and all
    // results are available.
    function eachAsync(arr, func, cb) {
        var doneCounter = 0,
            results = [];
        arr.forEach(function (item) {
            func(item, function (res) {
                doneCounter += 1;
                results.push(res);
                if (doneCounter === arr.length) {
                    cb(results);
                }
            });
        });
    }
    
    eachAsync(items, someAsyncFunc, console.log);
    

    Now, running node iterasync.js will wait for about three seconds and then print [ 'ONE', 'TWO', 'THREE' ]. This is a simple example, but it can be extended to handle many situations.

提交回复
热议问题