How to handle asynchronous operations in Vue.js with Promises?

To handle asynchronous operations in Vue.js with Promises, you can follow these steps:

  1. Import the axios library or any other library for making HTTP requests.
import axios from 'axios';
  1. Create a method in your Vue component that will handle the asynchronous operation. This method should return a Promise.
methods: { fetchData() { return new Promise((resolve, reject) => { // Perform asynchronous operation here axios.get('https://example.com/api/data') .then(response => { resolve(response.data); }) .catch(error => { reject(error); }); }); } }
  1. Call the method in your component's lifecycle hook or when a specific event occurs.
mounted() { this.fetchData() .then(data => { // Handle data after successful completion console.log(data); }) .catch(error => { // Handle error if the promise is rejected console.error(error); }); }

With this approach, you can make use of Promises to handle asynchronous operations in Vue.js. The then method is called when the Promise is resolved, and the catch method is called when the Promise is rejected. This allows you to handle both successful and error outcomes of the asynchronous operation.