I'm getting my knickers in a twist about asynchronicity, promises and fetch requests I'm afraid.
I'm trying to get data from a fetch request, simple enough you'd think, but all I'm getting is "Promise {pending}" when I run it. I've read 10s of answers that seem very similar to mine but nothing seems to work.
When I console.log(data.formatted_address) within the final then(), I get the result just fine (after the pending Promise), but when I just return it, only "Promise {pending}" in the final console.log. Any help would be much appreciated!
const fetch = require('node-fetch');
const dotenv = require('dotenv');
dotenv.config();
function getCoordinates(address) {
let searchAddress = address.split(" ").join("+");
let url =
"https://maps.googleapis.com/maps/api/geocode/json?address=" +
searchAddress +
"&key=" + process.env.GOOGLE_API;
return fetch(url)
.then(response => response.json())
.then(data => data.results[0].formatted_address)
}
let a = getCoordinates("Buckingham Palace, London")
console.log(a)
EDIT:
Here's a much simpler version without API calls if you wanna try it at home!
function getCoordinates() {
var promiseTest = new Promise(function(resolve, reject) {
if (1 + 1 === 2) {
resolve('pass')
} else {
reject('fail')
}
})
return promiseTest.then(data => data);
}
console.log(getCoordinates())
Further EDIT:
So I think I'm thinking about Promises & Asynchronicity wrong. I need to do a little reading up about then. I'm going to stay away from using async functions and just extend my promises to include the callbacks. But thanks all for the help!