Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取json数据时如何摆脱承诺_Javascript_Vue.js - Fatal编程技术网

Javascript 获取json数据时如何摆脱承诺

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) =>

我试图简单地从天气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) => 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);
    }
  }