简体   繁体   中英

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?

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

try this

const handleZipBtn = async () => {
    const zipVal = zipLine.value;
    const theAnswer = await getThatZip(zipVal)
    console.log(theAnswer);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM