Last active
July 12, 2019 11:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks josh!