Skip to content

Instantly share code, notes, and snippets.

@Dangeranger
Last active July 12, 2019 11:50
Show Gist options
  • Save Dangeranger/bbffafcf86dc760687ac9bc8b9520812 to your computer and use it in GitHub Desktop.
Save Dangeranger/bbffafcf86dc760687ac9bc8b9520812 to your computer and use it in GitHub Desktop.
Code showing how to use Promises or Async/Await for making fetch requests.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Hello Promises!</h1>
<script>
async function getLatLongAsync(address) {
try {
// encodeURI(someString) converts the string to URL safe characters
const response = await fetch(`https://nominatim.openstreetmap.org/search/?q=${encodeURI(address)}&format=json`);
const object = await response.json();
return { lat: object[0].lat, long: object[0].lon };
} catch (e) {
throw new Error('Something went wrong!');
}
}
function getLatLongPromise(address) {
// 182 Main St.,Burlington,VT
// encodeURI(someString) converts the string to URL safe characters
const request = fetch(`https://nominatim.openstreetmap.org/search/?q=${encodeURI(address)}&format=json`);
request
.then((response) => response.json())
.then((object) => {
return { lat: object[0].lat, long: object[0].lon };
});
}
</script>
</body>
</html>
@djangokoenig
Copy link

thanks josh!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment