I have the following code and would like to know how I can implement a try / catch with async / await executing the same function:
import Vue from 'vue'
import axios from 'axios'
new Vue({
el: '#app',
data: {
skills: [],
},
mounted() {
axios
.get('http://localhost:8080/wp-json/api/v1/skills')
.then(response => {
this.skills = response
}).catch(err => (console.log(err)))
}
})
Thank you!
To use the async/await syntax, we need to wrap the axios. get() function call within an async function. We encase the method call with a try... catch block so that we can capture any errors, similar to the catch() method we used in the Promise version.
Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.
Axios is a promise-based HTTP client library for both browsers and Node. js applications, which means it can be used in both frontend JavaScript applications and backend Node servers. In this article, we will look at how to use Axios in a simple Vue. js application.
The await keyword causes your code to wait for that Promise to resolve. And whatever data is normally passed to your callback as an argument is instead returned. There is still an asynchronous AJAX call happening, but our code reads a bit more like synchronous code. The await keyword is syntactic sugar.
see code below:
var app = new Vue({
el: '#app',
async mounted() {
try{
let response = await axios.get('http://localhost:8080/wp-json/api/v1/skills')
this.skills = response
}catch(err){
console.log(err)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With