我正在尝试执行下面的代码,但我没有得到预期的输出。
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 updatedPath
3 updatedPath
1 updatedPath
3 updatedPath
实际输出:
1 updatedPath
1 updatedPath
3 updatedPath
3 updatedPath
答案 0 :(得分:0)
那么,你想要什么功能?您的代码完全按照您的说法执行,因为它从第二行再次调用函数[本身]。然后终于到了其余部分。
如果你想让它们交织在一起,你必须在函数内按顺序调用它们,而不是递归地调用它们。递归动作拖尾并最终成螺旋形,这会产生你看到的重复。
请尝试使用描述性名称(更长时间实际上更好)虽然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);
});
}
要获得您想要的效果,您不需要递归。只需按顺序调用更改即可。你有什么具体的目标?