从退回的承诺中获得PromiseValue

时间:2019-04-05 15:26:53

标签: javascript es6-promise

我搜索了StackOverflow并阅读了有关从返回的诺言中获取价值的主题,但是由于某些原因,这些示例对我不起作用。

我的代码:

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

promise中的console.log提供了良好的数据。但是调用getThatZip只会给我希望。有人可以指出我的错误吗?

2 个答案:

答案 0 :(得分:2)

由于JS是异步的,因此在解决承诺之前执行带有console.log(theAnswer);的行。您可以使用es6 async/await语法解决此问题,或者在then()块中进行控制台日志记录,以查看变量何时设置为已解析的Promise。

const handleZipBtn6 = () => { 
    const zipVal = zipLine.value; 
    const theAnswer = getThatZip6(zipVal).then(res => { 
        console.log({ promiseIsResolved: res }) 
    }); 
};

答案 1 :(得分:2)

尝试

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