javascript - Functional Programming in Node.js - Wait for completion of function -


i beginner node.js. syntactically happy javascript having used build web uis. have tones of oop experience in java , c#, , understand functional programming basics. however, once complexity gets above point start find challenging.

i building node module incorporates other modules have written. each work fine on own, trying incorporate them together.

var miner = require("./miner"),     dbpedia = require("./dbpedia");  exports.getentities = function(uri, callback) {     miner.extractentities(uri, function (entities) {         var final = [];          entities.foreach(function (element, index) {             var newentity = {                 id : element.id,                 title : element.title,                 weight : element.weight,                 uri : ""             };              dbpedia.getentities(element.title, function(entity) {                 if (entity.length > 0) {                     newentity.uri = entity[0].uri[0];                 }                  final.push(newentity);             });         });          callback(final);     }); }; 

the question have how put can call callback once final populated. sure simple, struggling work out. suspect might have reverse order, don't see how it.

assuming dbpedia.getentities asynchronous function, problem foreach loop won't wait on each iteration function complete. slaks said, easiest route use library such async. these libraries have asynchronous loops. async.eachseries replace foreach, above async.map saves defining final array.

var miner = require("./miner"), dbpedia = require("./dbpedia"), async = require("async");  exports.getentities = function(uri, callback) {   miner.extractentities(uri, function (entities) {     async.map(entities, function(entity, callback) {       var newentity = {         id : entity.id,         title : entity.title,         weight : entity.weight,         uri : ""       };        dbpedia.getentities(element.title, function(entity) {         if (entity.length > 0) {           newentity.uri = entity[0].uri[0];         }          callback(null, newentity);       });      }, function(err, results) {       callback(null, results);     });   }); }; 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

html - How can i make an element from a bottom stacking context stays in front of another higher stacking context? -

sql - MySQL Custom calculate views -