0

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()
                    })
            });
        }
zAnthony
  • 332
  • 4
  • 17
  • 2
    there is no benefit to wrapping a promise in another promise here. maybe the dev was using the non-promised callback variation of the axios call, in which case it would make a tiny bit of sense, otherwise this is just bad code – Josh Apr 18 '20 at 15:42
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Apr 18 '20 at 15:54
  • Is there really no `return` statement in the `loadCustomer` function? If so, the promise is doubly useless, you're right. – Bergi Apr 18 '20 at 15:55

1 Answers1

3

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,

BeHappy
  • 3,705
  • 5
  • 18
  • 59