从返回的 Promise 中获取 PromiseValue

Get PromiseValue out of Returned Promise

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

我的代码:

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 只会给我承诺。有人可以指出我的错误吗?

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

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

试试这个

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