-2

I'm trying to achieve the URL tracking with below custom made script that extracts the json data that is in array and prints in console.log successfully

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";
   }
});
}

So above code prints data in console.log but doesn't returns the data! It always says undefined?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vicky Malhotra
  • 340
  • 1
  • 4
  • 13

1 Answers1

1

Your return is inside an arrow function inside a promise chain inside the redirecTrace function. So it is returning the value from the inner arrow function, but that does not apply to the outer function. What you want is to also return the promise (put return before the fetch() call). Then you can do this:

redirecTrace(url).then(returnValue => {
  // Do something with the returned value
});
Caleb Miller
  • 1,022
  • 9
  • 14
  • still can't figure out, i've got low knowlege of js.....added return before fetch call like this: https://imgur.com/a/7mLoZ7k but still didn't worked, i guess i'm doing this in wrong way... – Vicky Malhotra Dec 04 '20 at 21:41
  • @VickyMalhotra Your code looks good, but you still can't expect to access the returned inner value synchronously because the `fetch` is asynchronous. Once one part of your code is async, everything that depends on it must also be async. That's where the code snippet in my answer is needed. You call your function and it now returns a promise, which you wait on via `then` to get the inner return value you're looking for. For even more detail about why, and other options, see the linked answer that someone marked your question as a duplicate of. – Caleb Miller Dec 05 '20 at 02:46
  • Hey thanks for the explanation so i've added the return before `fetch()` call and tried to pass and get return value using `redirecTrace(urltoassign).then(urltoprint=> { jsontest = urltoprint; }` In the main code, here **urltoassign** is the url value that need to pass to the fetch function! & **urltoprint** is a var response that matches the regex function in fetch function[**urltoprint = response.match(regex);**] but still getting the undefined value! – Vicky Malhotra Dec 05 '20 at 09:14
  • Any code that needs the `urltoprint` value also needs to be placed inside the `then()`. Can you do that? – Caleb Miller Dec 05 '20 at 16:39
  • 1
    Alright got it and thanks just got a fix :) – Vicky Malhotra Dec 05 '20 at 16:46