I was following a vue.js tutorial and saw something that confuses me and was wondering if someone can explain it to me since I never use promise. The below method is used to assign a customer array object. Why use a Promise? I thought Promise should be used when you are returning an object to a service consumer? Why and when should I use a promise?
loadCustomer() {
new Promise((resolve, reject) => {
axios.get(this.DetailsDataUrl)
.then(res => {
this.Customer = res.data
resolve()
})
.catch(err => {
console.log(err);
reject()
})
});
}
With promises
you can call asynchronous
functions.
e.g. here when you want to use loadCustomer
you can await
until this function resolve or reject:
try {
// resolve
const response = await loadCustomer()
} catch(err) {
// reject
console.log(err)
}
axios
it self return a promise
:
so you can rewrite your function like this:
loadCustoemr() {
return axios.get(this.DetailsDataUrl)
}
and call it:
loadCutomer()
.then(res => this.Customer = res.data)
.catch(err => console.log(err))
as above you can also use async/await
here.
for more information you can use this link,