Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Take a look at <a href="https://github.com/kriskowal/q" rel="nofollow">Q</a> for ways to flatten callbacks (the code would be little nicer). For your specific example, I would prefer to refactor using a number of methods:</p> <ol> <li>Return methods early when err (saves you from having to nest else's)</li> <li>Execute asynchronous calls concurrently when they're not dependent (notice DB.cityGet and DB.iBuildings.find - makes your code run faster as well)</li> <li>creating functions and referencing outside the nest (ex. checkComplete)</li> </ol> <p>My refactor below:</p> <pre><code> DB.cityUpdateUpkeep = function( cuid ){ /** @type {Array} */ var buildings = null; var city = null; var checkComplete = function(){ if (!city || !builings){ return; } var income = city.resources.income; var storage = city.resources.storage; var stored = city.resources.stored; for( var buildingID in buildings ){ var building = buildings[ buildingID ]; var blueprint = DB.bBuildings[ building.buid ]; if( blueprint.resources.income ){ income = Utils.sumObjects( income, blueprint.resources.income ); } if( blueprint.resources.storage ){ storage = Utils.sumObjects( storage, blueprint.resources.storage ); } if( blueprint.resources.stored ){ stored = Utils.sumObjects( stored, blueprint.resources.stored ); } } console.log( "cuid: " + city._id + " income: " + income + " storage " + storage + " stored " + stored ); } DB.cityGet(cuid, function(err, response){ if (err){ console.log("Couldn't get city"); return; } city = response; checkComplete(); }); DB.iBuildings.find({cuid:cuid}, function(err, cursor){ if (err){ console.log(err); return; } cursor.toArray(function(err, response){ if (err){ console.log(err) return; } buildings = response; checkComplete(); }); }); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload