简体   繁体   中英

Why use a promise when making an axios api call?

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. eg 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 ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM