Underscore _.each callback when finished?

后端 未结 2 1258
梦毁少年i
梦毁少年i 2020-12-15 06:43

Is there a callback for when underscore is finished it\'s _.each loop because if I console log immediately afterwards obviously the array I am popu

相关标签:
2条回答
  • 2020-12-15 07:22

    The each function in UnderscoreJS is synchronous which wouldn't require a callback when it is finished. One it's done executing the commands immediately following the loop will execute.

    If you are performing async operations in your loop, I would recommend using a library that supports async operations within the each function. One possibility is by using AsyncJS.

    Here is your loop translated to AsyncJS:

    async.each(data.recipe, function(recipeItem, callback) {
        var recipeMap = that.get('recipeMap');
        recipeMap[recipeItem.id] = { id: recipeItem.id, quantity: recipeItem.quantity };
        callback(); // show that no errors happened
    }, function(err) {
        if(err) {
            console.log("There was an error" + err);
        } else {
            console.log("Loop is done");
        }
    });
    
    0 讨论(0)
  • 2020-12-15 07:23

    Another option is to build your callback function into the each loop on the last execution:

    _.each(collection, function(model) {
        if(model.collection.indexOf(model) + 1 == collection.length) {
             // Callback goes here
        }
    });
    

    Edit to add:

    I don't know what your input/output data looks like but you might consider using _.map instead, if you're just transforming / rearranging the contents

    0 讨论(0)
提交回复
热议问题