【问题标题】:Console.log prints the data but function doesn't return data [duplicate]Console.log 打印数据但函数不返回数据[重复]
【发布时间】:2021-03-16 22:27:16
【问题描述】:

我正在尝试使用以下自定义脚本实现 URL 跟踪,该脚本提取数组中的 json 数据并成功打印在 console.log 中

function redirecTrace(url){
var urltoprint = [];
  fetch("https://redirecttraceservice.com/api/v1/header-checker?initialURL="+url, {
  method: "POST"
})
.then(response => response.text()).then((response) => {
   var regex = new RegExp(/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^"\s]{2,}) - Response 20[01]/);
   
   if(response.match(regex)){
      urltoprint = response.match(regex);
      console.log(encodeURIComponent(urltoprint[1]));
      return ("This is from return: " + urltoprint[1]);
   }else{
      console.log("Destination URL Not Found");
      return "Destination URL Not Found";
   }
});
}

所以上面的代码在 console.log 中打印数据但不返回数据!它总是说 undefined?

【问题讨论】:

    标签: javascript api fetch fetch-api


    【解决方案1】:

    您的return 位于redirecTrace 函数内的承诺链内的箭头函数内。所以它从内部箭头函数返回值,但这不适用于外部函数。你想要的也是返回承诺(在fetch() 调用之前放置return)。然后你可以这样做:

    redirecTrace(url).then(returnValue => {
      // Do something with the returned value
    });
    

    【讨论】:

    • 还是想不通,我对 js 的了解很少......在 fetch 调用之前添加了 return 像这样:imgur.com/a/7mLoZ7k 但仍然没有工作,我想我'我以错误的方式这样做......
    • @VickyMalhotra 您的代码看起来不错,但您仍然不能期望同步访问返回的内部值,因为 fetch 是异步的。一旦你的代码的一部分是异步的,依赖它的所有东西也必须是异步的。这就是需要我的答案中的代码 sn-p 的地方。你调用你的函数,它现在返回一个promise,你通过then 等待它来获取你正在寻找的内部返回值。有关原因和其他选项的更多详细信息,请参阅有人将您的问题标记为重复的链接答案。
    • 嘿,感谢您的解释,所以我在fetch() 调用之前添加了返回值,并尝试使用redirecTrace(urltoassign).then(urltoprint=> { jsontest = urltoprint; } 传递并获取返回值在主代码中,这里是 urltoassign 是需要传递给 fetch 函数的 url 值! & urltoprint 是一个 var 响应,匹配 fetch function[urltoprint = response.match(regex);] 中的正则表达式函数,但仍然得到未定义的值!
    • 任何需要urltoprint 值的代码也需要放在then() 内。你能做到吗?
    • 好的,谢谢,刚刚解决了 :)
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多