0

I'm trying to extract information from a Promise returned by a fetch call. I don't seem to be able to do this. Either I get an undefined or I get another Promise, rather then the actual content of the promise itself. For example:

     async function fetchCoordinates(pluscode) {
       let response = await fetch(url.replace("${pluscode}", pluscode));
       return await response.json();
     }
     
     function getCoordinates(pluscode) {
       let geoinfo;
       fetchCoordinates(pluscode).then(info => {geoinfo = info})
       return geoinfo
     }
   
     geoinfo = getCoordinates("{{ place.pluscode }}");

When evaluated, geoinfo is undefined (instead of an object). However, if I change this line:

fetchCoordinates(pluscode).then(info => {geoinfo = info})

to:

fetchCoordinates(pluscode).then(info => {console.log(info)})

Then the object is saved logged correctly to the console.

Edgar Derby
  • 2,543
  • 4
  • 29
  • 48
  • 4
    You extract the value by using `await`. Or chain a `.then()`. Once a value is a promise, you must treat it as a promise forever. – VLAZ Nov 09 '21 at 06:34
  • I'm using await and still it doesn't work. @VLAZ At some point I want to store the information of fetch into a variable and I seem unable to do that. – Edgar Derby Nov 09 '21 at 06:41
  • @EdgarDerby async functions *always* return a promise. Just because you've used `await` in an async function doesn't mean it produces a plain value. It is not possible to convert async code to synchronous one like you've tried with `return await`. – VLAZ Nov 09 '21 at 06:43
  • I continue not to understand and now that the question is closed I can't even get more information about my specific case. :( The questions linked above do not help... – Edgar Derby Nov 09 '21 at 07:26
  • @EdgarDerby The questions linked above explain the general case. Try to understand them! You're right, it is impossible to synchronously extract the information, you always get another promise. Use it like a promise. – Bergi Nov 09 '21 at 08:58

0 Answers0