【问题标题】:Javascript Callback in for Loopfor循环中的Javascript回调
【发布时间】: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


【解决方案1】:

您的循环应该调用另一个保留 y 值的函数,如下所示:

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) {
              yourNewFunction (y, caps, parent);
          }}}
}

function yourNewFunction (y, caps, parent) {
  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);
        }
});
}

【讨论】:

  • 感谢您的帮助,但我通过调用您上面建议的另一个函数得到相同的结果....
【解决方案2】:

有两种方法可以做到这一点。 将循环放在一个函数中,在循环完成后执行你的回调。 (如果您在循环内进行异步调用,则会出现问题。

function doLoopdiloopStuff() {
 for() {
 }
 callback();
}

另一种方式,我更喜欢的方式是这样的:

for(var i = 0; i < stuff || function(){ /* here's the callback */ }(), false; i++) {
  /* do your loop-di-loop */ 
}

再举一个例子:

for (var index = 0; index < caps.length || function(){ callbackFunction(); /* This is the callback you are calling */ return false;}(); index++) {
            var element = caps[index];
            // here comes the code of what you want to do with a single element
}

【讨论】:

  • 感谢您的帮助,但我正在努力将您的提示转换为我的示例......在我上面的示例中,'stuff' 将是 'caps.length' 对吗? '||' 之后的部分我不太清楚....
  • 是的。东西是你的 caps.length。 “||”是这种形式的或。你所有的大写物品也是如此。之后进入函数。在函数内部,您可以构建回调。返回值或从中调用另一个函数。
  • 好吧,我无法让它工作......我所做的只是在“||”之后简单地编写 getChildContent 函数在循环中......但它不起作用......你是什么意思'你可以在这里建立你的回调'......
  • 查看编辑。可能是新添加的cmets,到最后一个例子可以帮助你更好的理解。
  • 感谢您对我的耐心,但我不知道如何将您的示例转移到我的示例中...尤其是循环中的函数...
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
相关资源
最近更新 更多