【问题标题】:How to debug this Node script?如何调试这个节点脚本?
【发布时间】:2017-01-21 08:32:41
【问题描述】:

我正在尝试执行以下代码,但没有得到预期的输出。

recursive(prodURL, function(err, files) {
    targetDeviceUpdate("updatedPath");   
});
function targetDeviceUpdate(sourceImages, updatedPath) {
    console.log("1 " + updatedPath);
    recursive(prodURL + "/device", function(err, files) {
        console.log("3 " + updatedPath);
    });
}

预期输出:

1 个更新路径

3 更新路径

1 个更新路径

3 更新路径

实际输出:

1 个更新路径

1 个更新路径

3 更新路径

3 更新路径

【问题讨论】:

  • 你能提供你的“递归”函数吗?

标签: javascript node.js closures


【解决方案1】:

嗯,你想要什么功能?您的代码完全按照您的说法执行,因为它从第二行再次调用函数 [自身]。然后终于到了剩下的部分。

如果您希望它们交织在一起,则必须在函数内按顺序调用它们,而不是递归调用。递归动作尾随并最终呈螺旋式上升,从而产生了您所看到的这种重复。

请尝试使用描述性名称(实际上越长越好),虽然 CamelCase 很好,但我更喜欢连字符作为命名变量,但是,由于 javascript 不会将连字符解释为减号,因此您可以使用 underscores_to_name_your_variables_cleanly。

the_method_thatinvokes_target_device_update(prodURL, function(err, files) {
  target_device_update("updatedPath");   
});

function target_device_update(sourceImages, updated_path) {
  console.log("Here is the first line: " + updated_path);
  the_method_that_invokes_target_device_update(prodURL + "/device", function(err, files) {
    //invoking this function will naturally call the first line again before reaching the rest of the code.

    //and this 'callback' or 'remainder' code gets called only after, and twice at that.
    console.log("3 " + updated_path);

  });
}

为了得到你想要的效果,你不需要递归。只需按顺序调用更改。您具体想达到什么目标?

【讨论】:

  • 两个递归函数有不同的用途。我每次使用超过 1500 个文件。
  • @golekunal88 在不同的功能中做不同的工作
猜你喜欢
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 2017-01-29
  • 2019-08-15
  • 1970-01-01
  • 2015-10-23
相关资源
最近更新 更多