我目前正在尝试了解 Node 和回调,并尝试了对此代码的各种解决方案以使其正常工作,但是 param2 返回未定义。有人能告诉我为什么吗?以及如何解决这个问题?谢谢!
function getPage(callback) {
url = 'http://www.google.com';
if (url) {
url = url;
} else {
console.log('There was an error. No URL submitted');
}
callback(url, param2);
}
function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}
getPage(CB);
最佳答案
这是因为 param2
在您调用回调函数的范围内未定义。要让 param2
重新定义,请确保 param2
已在 getpage()
function getPage(callback) {
url = 'http://www.google.com';
// **make sure param2 is defined**
var param2 = "param2 value"
if (url) {
url = url;
} else {
console.log('There was an error. No URL submitted');
}
callback(url, param2);
}
function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}
getPage(CB);
关于javascript - Node 回调 - 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552746/