[英]Functional Programming in Node.js - Wait for completion of function
I am a beginner with Node.js. 我是Node.js的初学者。 Syntactically I am happy with JavaScript having used it to build web UIs. 从语法上讲,我对JavaScript用来构建Web UI感到满意。 I have tones of OOP experience in Java and C#, and I understand functional programming basics. 我具有Java和C#的OOP经验,并且了解函数式编程基础。 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. 我正在构建一个Node模块,其中包含了我编写的其他一些模块。 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. 我的问题是如何将所有这些放在一起,以便在final
填充完后可以调用callback
。 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. 假设dbpedia.getEntities是一个异步函数,则问题在于forEach循环不会在每次迭代中等待该函数完成。 Like SLaks said, the easiest route is to use a library such as async. 就像SLaks所说的那样,最简单的方法是使用async之类的库。 These libraries have asynchronous loops. 这些库具有异步循环。 async.eachSeries would replace the forEach, but as above the async.map saves you defining the final array. async.eachSeries将替换forEach,但如上所述,async.map可以节省您定义最终数组的时间。
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);
});
});
};
您想使代码同步,那里有很多库可以做到这一点,有趣的方法之一是节点同步
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.