Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore _.each callback when finished?

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 populating with the each loop is not available. This is from a nested _.each loop.

_.each(data.recipe, function(recipeItem) {
    var recipeMap = that.get('recipeMap');
    recipeMap[recipeItem.id] = { id: recipeItem.id, quantity: recipeItem.quantity };
});
console.log(that.get('recipeMap')); //not ready yet.
like image 400
Johnston Avatar asked Sep 16 '13 15:09

Johnston


People also ask

What does _ each do?

The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is underscore in react?

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

Is underscore JS still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.


1 Answers

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");
    }
});
like image 64
jrthib Avatar answered Sep 21 '22 06:09

jrthib