Reputation: 157
I have searched StackOverflow and read the topics on getting values from returned promises but for some reason those examples aren't working for me.
My code:
const getThatZip = (zip) => new Promise((resolve, reject) => {
const query = `http://api.zippopotam.us/us/${zip}`;
const request = new XMLHttpRequest();
request.addEventListener('readystatechange', (e) => {
if (e.target.readyState === 4 && e.target.status === 200) {
const data = JSON.parse(e.target.responseText);
//console.log(data.places[0]['place name'] + ', ' + data.places[0]['state abbreviation']);
resolve(data.places[0]['place name'] + ', ' + data.places[0]['state abbreviation'])
} else if (e.target.readyState === 4) {
reject('An error has occurred')
}
});
request.open('GET', query);
request.send();
});
const handleZipBtn = () => {
const zipVal = zipLine.value;
const theAnswer = getThatZip(zipVal).then((result) => {
return result
});
console.log(theAnswer);
};
The console.log inside the promise gives good data. But calling getThatZip only gives me the promise. Can someone point out my error?
Upvotes: 0
Views: 718
Reputation: 970
try this
const handleZipBtn = async () => {
const zipVal = zipLine.value;
const theAnswer = await getThatZip(zipVal)
console.log(theAnswer);
};
Upvotes: 2
Reputation: 129
Since JS is asynchronous, the line with console.log(theAnswer);
is executed before the promise is resolved. You can solve this using es6 async/await
syntax, or do your console logging within the then()
block to see when the variable is set to the resolved promise.
const handleZipBtn6 = () => {
const zipVal = zipLine.value;
const theAnswer = getThatZip6(zipVal).then(res => {
console.log({ promiseIsResolved: res })
});
};
Upvotes: 2