【发布时间】:2015-10-15 11:20:49
【问题描述】:
我的问题是我有一个Function A,它在某个时候调用另一个函数,我们称之为Function B (getChildContent) 并且需要Function B 的返回值才能继续。我知道这是因为 Javascripts 异步性质,我试图通过回调来解决它。但我无法让它正常工作。
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
//var content = getChildContent(caps[y]);
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}}}
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
所以在Function A 中,我试图从 for 循环调用 getChildContent 并从 caps-array 传递当前字符串。对于 caps-array getChildContent() 中的每个字符串,通过 node.js 模块发出一个 http 请求并检索一个字符串。使用此字符串,我正在构建Function A 中需要的对象(内容)以继续。然而,Function A 中的 'console.log(content)' 只是打印出使用 caps-array 中的最后一个字符串创建的对象,但要打印很多次。例如。如果 caps-array 有 5 个条目,我将得到使用 caps-array 的最后一个条目创建的对象的 5 倍。
我如何管理循环/回调以每次在我的控制台上获取正确的对象?
【问题讨论】:
-
这行不通。当你的回调函数被调用时,你的 y 变量已经改变了它的值。
-
你试过
Function.prototype.bind吗? -
@EugenTimm 我知道它不起作用,你有什么提示让它起作用吗?
-
@klenium 对不起,我是 javascript 新手,不知道你想告诉我什么...
标签: javascript arrays loops callback