Getting JSON data without having to rely on promises

Trying to fetch data from a weather API using the provided link:

The api.js file contains a basic function:

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

In Vue component, calling the function as follows:

export default {
  data: () => ({
    currentWeather: []
  }),
  created: function () {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.showPosition);
    }
  },
  methods: {
    showPosition(position) {
      const data = api.getCurrent(position.coords.longitude, position.coords.latitude);
      this.currentWeather = data;
      console.log(this.currentWeather);
    }
  }
}

The console log shows a pending Promise object, not retrieving data properly. Looking for a solution to resolve this issue.

If anyone has a code-based solution, please share. Thank you!

Answer №1

To eliminate the Promise and retrieve its data, utilize .then() within the result of .getCurrent(), similar to how you would with fetch():

  methods: {
    showPosition(position) {
      api.getCurrent(position.coords.longitude,position.coords.latitude)
        .then((data) => {
          this.current = data;
          console.log(this.current);
        }
    }
  }

Alternatively, you can define showPosition as async, and use await:

  methods: {
    showPosition: async function(position) {
      const data = await api.getCurrent(position.coords.longitude,position.coords.latitude);
      this.current = data;
      console.log(this.current);
    }
  }

Remember that both approaches will handle the results asynchronously, so this.current won't immediately have the value of data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Countdown Timer App using Flask

I'm currently working on a Flask-based game that involves countdown timers for each round. My goal is to have the timer decrease by 1 second every round without the need to reload the page. I've tried using time.sleep in my Python code to update ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Issue: Encountered a problem when attempting to encode the data type ([object Object]) into a Firestore Value while using Node

While attempting to insert a document with the geopoint dataType in firestore using the following instance: new firebase.firestore.GeoPoint(latitude, longitude) I encountered the following error. https://i.sstatic.net/yKuIs.png ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Removing other objects with Mongoose after an update

I'm facing an issue with my update query in mongoose. I can't figure out why other objects are getting deleted when I only intend to update one specific object. The code is functioning correctly in terms of updating, but it's causing all the ...

Use Jquery to modify the value of a data attribute when a key is released

When I am adding some HTML to a document, one part includes a text input field. My goal is to update the value of the closest li element's data attribute whenever information is typed into this input field. Unfortunately, this functionality is not cu ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

Rollback feature in Vue Pinia store for reverting changes

Let's say I have a list of persons in my application that is populated from the state of a 'persons' object in my store. When I click on a person, I am taken to a 'detail' page for that person where I can edit their information. H ...

Concealing and revealing an image with the onMouseOver and onMouseOut events - image quickly reemerges

After writing the following jQuery script, I encountered an issue. <script type="text/javascript"> $(document).ready(function(){ $('#Oval-1').on('mouseover', function(e) { $("#Oval-1").fadeOut ...

Utilizing Vuex, is it possible to filter an array by incorporating another array in a Javascript view?

When using VueX, I am attempting to filter my "ListJobs" array based on the currentTag. Essentially, I want to return elements that match any of the values in the currentTag array with the rows role, level, languages, and tools. state: [ listJobs: ...

How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement: Math.random() > 0.5 ? 'spikes' : 'slime' I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those th ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...

Instructions on displaying a pop-up message upon clicking the edit button with the use of javascript

How can I display a popup message box when the edit button is clicked on my PHP page? I want to confirm before passing data to the edit page, but currently, the data is being sent without displaying any message. Any suggestions on how to fix this issue w ...

error related to reserved area in jquery message box

Currently, I am exploring a jQuery message box similar to the one featured in this example. While I am eager to integrate it into my web application, I have run into an issue. Specifically, I am facing a problem with the reserved area of the entire popup. ...

Retrieve the element referred to as $el within a computed property

When attempting to retrieve this.$el.offsetTop within a computed property, the following error occurs: Cannot read property 'offsetTop' of undefined Is there a way to access the component's offsetTop in a computed method? If not, what is t ...

Adding an active class to dynamic tabs in Vue.js navigation

I'm currently facing a challenge in adding an active class to a specific element for tabs navigation using vue.js. One of the obstacles I'm encountering is my limited experience with Vue, as well as the fact that the navigation items are being ge ...

Click on an image to dismiss a material-ui dialog

Trying to include a clickable image to close a material-ui dialog, but encountering an issue where the onClick event is not responding. The props.onRequestClose function works fine when clicking outside of the dialog. What could be causing this problem? ...

Encountering a problem with vis js events

While constructing a timeline in my vue.js application, I opted to utilize vis.js. Unfortunately, I encountered some issues when attempting to incorporate events. Initially, setting @drop="myDropCallback()" did not trigger the function upon dropping an ite ...