【问题标题】:Code won't execute in function containing return?代码不会在包含返回的函数中执行?
【发布时间】: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


【解决方案1】:

// 创建一个异步函数来等待任何异步代码。否则会出错。

async function main() {

      let groupAname = "Old World sparrow";
      // Await for the promise to be resolved. // Like pause call
      const birds_array = await groupA(groupAname);
      // Result done, print
      console.log(birds_array)
    }
main()

示例:

const delayData = (num) => {
  return new Promise((r) => {
    setTimeout(() => {
      r(num);
    }, 1000);
  });
};
async function main() {
  const num = await delayData(1);

  console.log(num); // 1
  const num2 = await delayData(2);

  console.log(num2); // 2
}
main();

// Using then

delayData(1).then(num => {
  console.log(num) // 1
})
delayData(2).then(num => {
  console.log(num) // 2
})

【讨论】:

  • 好的开始明白了。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多