I'm trying to get data from a API to a variable for Geocoding, I use fetch to get API response like this:
var requestOptions = {
method: 'GET',
};
fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.then(data=>{jsonData=data;})
.catch(error => console.log('error', error));
(In my code I use my actual keyAPI)
I need to get the data so I can get the latitude and longitude in the following lines, but because fetch is a promise, I'm unable to add it to a variable. The values appear in browser console.
How can I add it to a variable, I have seen that some people use async I tried this way:
async function fetchText() {
let response = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.then(data=>{jsonData=data;})
.catch(error => console.log('error', error));
let data = await response.text();
console.log(data);
}
fetchText();
But it gives:
"Uncaught (in promise) TypeError: Cannot read properties of undefined"
My intent with await:
async function funcionAsincrona(){
const responses = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
return responses;
}
let responses=funcionAsincrona();
but responses is like this:
Promise {}[[Prototype]]:... "Promise"[[Prototype]]: Object[[PromiseState]]: "fulfilled"[[PromiseResult]]: undefined
How can I make it work?