Search code examples
javascriptes6-promise

Get PromiseValue out of Returned Promise


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?


Solution

  • 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 }) 
        }); 
    };