Javascript 获取json数据时如何摆脱承诺
我试图简单地从天气API获取数据。这是我的api链接 在我的api.js文件中,我有以下基本功能:Javascript 获取json数据时如何摆脱承诺,javascript,vue.js,Javascript,Vue.js,我试图简单地从天气API获取数据。这是我的api链接 在我的api.js文件中,我有以下基本功能: const baseUrl = `http://api.wunderground.com/api/5b81d144ae2d1942/conditions/q`; export const getCurrent = (lat,lon) => { return fetch(`${baseUrl}/${lon},${lat}.json`) .then((response) =>
const baseUrl = `http://api.wunderground.com/api/5b81d144ae2d1942/conditions/q`;
export const getCurrent = (lat,lon) => {
return fetch(`${baseUrl}/${lon},${lat}.json`)
.then((response) => response.json())
.then((json) => {
console.log(json.current_observation.weather)
return json.current_observation
})
.catch(() => {
console.error('unable to fetch tasks')
})
}
注意console.log,在这个函数中,我能够获取json数据,我得到了我想要的值
现在,在我的Vue中,我这样调用此函数:
export default {
data: () => ({
current: []
}),
created: function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
}
},
methods: {
showPosition(position) {
const data = api.getCurrent(position.coords.longitude,position.coords.latitude);
this.current = data;
console.log(this.current);
}
}
}
出于某种原因,这里的console.log提供了以下信息:
Promise {<pending>}__proto__:
Promise[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
Promise{}\u协议:
承诺[[承诺状态]]:“已解决”
[[PromiseValue]]:对象
我不知道发生了什么,但我无法访问数据。我在网上搜索过,很多页面都在谈论这个问题,但找不到确切的答案,只有长文本
是否有此问题的解决方案(请输入代码)
非常感谢。要“摆脱”承诺并访问其数据,请在.getCurrent()
的结果中使用,就像使用fetch()时一样:
或者,您可以将showPosition
声明为,并使用:
请记住,两次执行的结果都将异步处理,这意味着这一点。当前的不会立即具有数据的值
methods: {
showPosition(position) {
api.getCurrent(position.coords.longitude,position.coords.latitude)
.then((data) => {
this.current = data;
console.log(this.current);
}
}
}
methods: {
showPosition: async function(position) {
const data = await api.getCurrent(position.coords.longitude,position.coords.latitude);
this.current = data;
console.log(this.current);
}
}