简体   繁体   中英

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

I am a beginner with Node.js. Syntactically I am happy with JavaScript having used it to build web UIs. I have tones of OOP experience in Java and C#, and I understand functional programming basics. However, once the complexity gets above a certain point I start to find it challenging.

I am building a Node module which incorporates some other modules I have written. They each work fine on their own, but I am trying to 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 I have is how do I put this all together so that I can call callback once final is fully populated. I am sure it is something simple, but I am struggling to work it out. I suspect that I might have to reverse the order, but I don't see how to do it.

Assuming dbpedia.getEntities is an asynchronous function, the problem is the forEach loop won't wait on each iteration for the function to complete. Like SLaks said, the easiest route is to use a library such as async. These libraries have asynchronous loops. async.eachSeries would replace the forEach, but as above the async.map saves you defining the 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);
    });
  });
};

您想使代码同步,那里有很多库可以做到这一点,有趣的方法之一是节点同步

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM