javascript - 如何使用递归调用从函数返回 javascript 数据

标签 javascript recursion

<分区>

我有这个递归函数,我需要在函数完成后返回一些数据。

// Set Up my Database paramaters
var coachdb = new AWS.DynamoDB({
  ...
});

// This tracks the array index of the current parameter.
var pos = 0;

function callback(err, data) {
  if (err) { 
    console.log(err, err.stack);
  } else if (data.Items.length > 0) {

    //return data.Items  // Where I need something here to return data

  } else if (++pos < params.length) {      // Increment the index.
    coachdb.query(params[pos], callback);  // Recursive call.
  }
}

coachdb.query(params[pos], callback); // Kick off the series of calls

函数内的一切都运行良好。我正在查询我的数据库,遍历可能的参数直到找到正确的参数,然后函数结束。

但是我不确定如何将数据传递到函数外部。任何帮助将不胜感激。

最佳答案

这是不可能的,而不是返回您需要在回调中编写逻辑的数据。

编辑:如果您不想拥有困惑的代码,您需要重构您的代码并将代码提取到单独的方法中;

function callback(err, data) {
  if (err) { 
    errorLogic(err);
  } else if (data.Items.length > 0) {
    successLogic(data.Items);
  } else if (++pos < params.length) {      // Increment the index.
    coachdb.query(params[pos], callback);  // Recursive call.
  }
}

关于javascript - 如何使用递归调用从函数返回 javascript 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532493/

相关文章:

javascript - Material Ui 列表函数返回重复值

haskell - 从非递归的不可遍历构建列表

c - 递归函数

java - 递归对象设置java

javascript - 如何在登录页面中将鼠标指针自动放置在提交按钮上?

javascript - 根据页面向header添加react组件

javascript - 谷歌地图标记集群 : how to combine Interface Renderer and GridOptions gridSize in configuration object?

javascript - getElementsByClassName 更改输入值

java - 如何为组合编写递归函数

python - Jinja2 "recursive"标签实际上是如何工作的?