循环函数的返回值 [英] Return value from recurring function

查看:27
本文介绍了循环函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 Meteor 服务器递归方法 commonHint 返回 result undefined 到控制台,即使 finalRes 有一个值.
关于如何将 finalRes 返回给调用者的任何建议?谢谢

This Meteor server recursive method commonHint returns result undefined to the console even the finalRes has a value.
Any suggestion on how to return the finalRes to the caller? thx

  //call the recursive method
  let result = this.commonHint(myCollection.findOne({age: 44}), shortMatches);
        console.log('got most common hint: ' + result); // <=== undefined ====

  'commonHint': function (doc, shortMatches, hinters, results = []) {
      // first call only first 2 args are defined,
      if (!hinters) {
        hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)];
        this.commonHint(doc, shortMatches, hinters, results);  // hinters is an array of length 3 with 2 elements each
        return;
      }

      // get an element from hinters, use its 2 hinters and remove that element from the hinters
      let hintersToUse = hinters.pop();
      let hinter1 = this.cleanMatchItem(hintersToUse[0]);
      let hinter2 = this.cleanMatchItem(hintersToUse[1]);
      let intersect = _.intersection(hinter1, hinter2);

      // which item of the shortMatches best matches with the intersect
      let tempCol = new Meteor.Collection();
      for (let i = 0; i < shortMatches.length; i++) { tempCol.insert({match: shortMatches[i]}); }
      results.push(mostSimilarString(tempCol.find({}), 'match', intersect.join(' ')));

      if (hinters.length > 0) {
        this.commonHint(doc, shortMatches, hinters, results);
      } else {
        let finalRes = lib.mostCommon(results);
        console.log(finalRes);  //<==== has a value
        return finalRes;        //<==== so return it to caller
      }
    },

推荐答案

递归函数中返回结果的每个路径必须返回一个结果.在您的路径中,您有不提供的路径:当未提供 hinters 时,以及当 hinters.length >0 为真.

Every path out of a recursive function that returns a result must return a result. In yours, you have paths that don't: When hinters isn't provided, and when hinters.length > 0 is true.

你应该返回递归调用的结果:

You should return the result of the recursive call:

  if (!hinters) {
    hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)];
    return this.commonHint(doc, shortMatches, hinters, results);  // hinters is an array of length 3 with 2 elements each
//  ^^^^^^
  }

  // ...

  if (hinters.length > 0) {
    return this.commonHint(doc, shortMatches, hinters, results);
//  ^^^^^^
  } else {
    let finalRes = lib.mostCommon(results);
    console.log(finalRes);  //<==== has a value
    return finalRes;        //<==== so return it to caller
  }

这篇关于循环函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆