classWooCommerceProducts.js
import {
WooComRestApi
} from "~/plugins/classWooCommerceOrigin.js";
export class WooCommerceProducts {
constructor() {
}
//-- A method --
async get() {
const getproducts = await WooComRestApi.get("products").then((response) => {
return response.data
}).catch((error) => {
return "WooCommerceProducts get failre"
})
return getproducts
}
//or
//-- B method --
get() {
const getproducts = WooComRestApi.get("products").then((response) => {
return response.data
}).catch((error) => {
return "WooCommerceProducts get failre"
})
return getproducts
}
}
products.vue
// -- A method --
methods: {
getProducts() {
const WooComProducts = new WooCommerceProducts()
WooComProducts.get().then((response) => {
this.products = response
}).catch((error) => {
throw new Error(error)
})
}
},
or
// -- B method --
methods: {
async getProducts() {
const WooComProducts = new WooCommerceProducts()
await WooComProducts.get().then((response) => {
this.products = response
}).catch((error) => {
throw new Error(error)
})
}
},
guys a quick question on two part
i have a js class is calling from backend and get back products data, both code works, one is i async and await on the html vue the other one is i async await on the js class, so which one did right ? can anyone tell me what different dose it make ?
how do i return the data or the error back to the function getProducts and result same return as the class. if fail return "wooCommerceProducts : get failure" and it will return back to my getProducts catch error functions.
learning more ๐ greatful for sharing your advice. How will you implete if was you ?
The thing to remember is that async/await is just more modern syntax for promise .then(). It doesn't make sense to mix them.
how do i return the data or the error back to the function getProducts
Return the data explicitly in the async syntax (inside a try/catch). In the older promise style, return the promise.
//-- A method --
async get() { // note that no "then" appears here
try {
const response = await WooComRestApi.get("products");
return response.data; // note the return
} catch(err) {
console.log("WooCommerceProducts failure");
throw err;
}
}
//or, using the older syntax
//-- B method --
get() {
return WooComRestApi.get("products").then((response) => { // note the return
return response.data;
}).catch((error) => {
console.log("WooCommerceProducts get failure");
throw error;
});
}
i have a js class is calling from backend and get back products data, both code works, one is i async and await on the html vue the other one is i async await on the js class, so which one did right ?
Same pattern as before "A method" is correct because it doesn't need a return. For "B method", you've chosen the new style, so stick with it...
// -- B method --
methods: {
async getProducts() {
const WooComProducts = new WooCommerceProducts()
try {
this.products = await WooComProducts.get();
} catch(error) {
// handle error
}
}
},