gpt4 book ai didi

javascript - 从返回的 Promise 中获取 PromiseValue

转载 作者:行者123 更新时间:2023-11-28 14:20:07 25 4
gpt4 key购买 nike

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

我的代码:

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

最佳答案

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

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

关于javascript - 从返回的 Promise 中获取 PromiseValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55538803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com