for循环中的Javascript回调

Javascript Callback in for Loop

本文关键字:Javascript 回调 循环 for      更新时间:2023-09-26

我的问题是,我有一个Function A,它在一个点调用另一个函数,让我们称之为Function B (getChildContent),需要Function B的返回值才能继续。我知道这是因为javascript的异步性质,我试图用回调来解决它。但是我不能使它正常工作。

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-Loop调用getChildContent,并从caps-array传递当前字符串。对于caps-array中的每个字符串,getChildContent()通过node.js模块发出http请求并检索一个字符串。有了这个字符串,我正在构建一个对象(内容),这是需要在Function A继续。然而,Function A中的'console.log(content)'只是打印出用caps-array中的最后一个字符串创建的对象,但是多次。例如,如果caps-array有5个条目,我得到5倍于caps-array最后一个条目创建的对象。我怎么能管理循环/回调每次得到正确的对象在我的控制台上?

循环应该调用另一个保留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);
        }
});
}

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

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
}