是否可以在非阻塞回调函数中递归调用父函数?
例如:
function checkValidZip(zipInput) {
if (!zipInput.trim().match(/^(\d{5})$/g)) {
userInput("Please enter a valid 5 digit shipping zip code", function(zip){
//recursively call the parent function to check for valid zip
//(and continue to prompt the user until they enter proper zip)
return checkValidZip(zip);
});
}
//and return (only) the valid zip
return output(zipInput);
}
function userInput(param1, callback){
input = prompt(param1);
callback(input);
}
function output(param){
alert(param);
}
checkValidZip(prompt("hello"));
http://jsbin.com/omubab/1/edit
显然,问题在于代码将继续执行,而无需等待调用回调函数(因此在此示例中不检查 zip),并且直到父级返回后才会调用递归函数的其他迭代(在此示例中返回输出(zipInput);
)。
那么,是否可以有一个“自调用”递归函数作为回调?
最佳答案
在此特定示例中,您只需在 checkValidZip
末尾使用 else output(zipInput)
即可获得看似合理的行为。
更一般地说,您可能希望 checkValidZip
进行回调:
function checkValidZip(zipInput, callback) {
if (!zipInput.trim().match(/^(\d{5})$/g)) {
userInput("Please enter a valid 5 digit shipping zip code", function(zip){
//recursively call the parent function to check for valid zip
//(and continue to prompt the user until they enter proper zip)
checkValidZip(zip,callback);
});
}
//and return (only) the valid zip
else callback(zipInput);
}
checkValidZip(prompt("hello"),output);
关于javascript - 在非阻塞回调函数中递归调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16698944/