gpt4 book ai didi

javascript - Node 回调 - 为什么这不起作用?

转载 作者:行者123 更新时间:2023-11-28 18:50:31 28 4
gpt4 key购买 nike

我目前正在尝试了解 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com