To handle asynchronous operations in Vue.js with Promises, you can follow these steps:
axios
library or any other library for making HTTP requests.import axios from 'axios';
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);
});
});
}
}
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.