【发布时间】:2020-05-01 08:08:14
【问题描述】:
我在范围界定方面遇到了一些问题,我是 javascript 新手,因此对我的经验不足深表歉意。我遇到的问题是我不明白为什么function groupA(thename) 花括号内的console.log 不允许代码输出。在 Visual Studio 中,它会使代码变灰。我认为这可能是由于return fetch(`${url}${thename}`),因为当我删除该返回时代码不会变灰。 return 函数为什么会这样呢?
我的目标是将每个函数正确链接在一起,以便推送到birds_array 的数据可以通过groupA 函数返回。我将如何正确格式化这些函数以使其成为可能?
const birds_array = []
let groupAname = "Old World sparrow"
groupA(groupAname);
function groupA(thename) {
return fetch(`${url}${thename}`)
.then(response => response.text())
.then(body => {
const $ = cheerio.load(body);
$('.llgymd').each( (index, element) => {
const $element = $(element);
const names = $element.text();
groupA_array[index] = names;
});
groupA_loop()
function groupA_loop(){
for(j = 0; j < groupA_array.length; j++){
if(!birds_array.includes(groupA_array[j])){
birds_array.push(groupA_array[j]);
}
// code functions here
console.log(birds_array);
}
// code functions here
console.log(birds_array);
}
// code functions here
console.log(birds_array);
});
// code does not function here
console.log(birds_array);
}
【问题讨论】:
-
console.log(birds_array);是死代码...这是异步功能。你必须使用 then 来获得价值
-
好有趣,你能给我举个例子吗?
-
听起来您已经知道解决方案了,正如您所见,在
then回调中console.log语句有效。 -
所有工作的 console.log 都在您的 return 语句中,也就是说,如果您遵循 {},您会看到最后一个 console.log 在 return 之后。那是“死”代码,因为在返回完成后执行离开了函数。
-
在答案中添加基本示例。请检查
标签: javascript