I've been delving into Axios and promises lately, trying to grasp the concept. It seems like I'm on the right track, but there are definitely some mistakes in my approach. My javascript method is supposed to return a promise, within which I have an Axios post request with two chained .then
methods. Whenever the initial post fails, I encounter an unsightly error in the console:
Unhandled promise rejection ReferenceError: "reject is not defined"
. I suspect that nesting the .catch
methods might be the issue here, and perhaps it should simply be post.then.then.catch
.
Moreover, I am puzzled as to why the itemInformation is not being returned in the response
within the second .then
block. Can anyone shed light on this?
Check out the relevant Javascript code (the addToCartVue
method is invoked first):
addToCartVue(itemData) {
let vm = this;
return new Promise((resolve, reject) => {
vm.buildDataString(itemData);
axios.post(POST_ENDPOINT, {
data: vm.dataString
},
{
/*headers: {
"Content-Type": "application/x-www-form-urlencoded"
}*/
}).then(response => {
return vm.updateCartInfo(vm.dataString, itemData.addToCartParameters.itemId, vm.selectedStoreId, vm.quantity);
}).then(response => {
if (itemData.addToCartParameters.showLB) {
vm.emitGlobalEvent('addToCart::open', itemData);
resolve(response);
}
}).catch(error => reject(error));
}).catch(error => reject(error));
}, // end of addToCartVue method
buildDataString(itemData) {
// irrelevant code that builds quantity and dataString variables
vm.quantity = quantity;
vm.dataString = dataString;
}, // end of buildDataString method
updateCartInfo(dataString, itemId, selectedStore, quantity) {
axios.get(GET_ENDPOINT, {
params: {
data: dataString
}
}).then(response => {
cartDropDown.populateCartDropDown(response);
const addedItem = response.addedItem;
const basketInfo = response.basketInfo;
let productQuantity = quantity;
if (addedItem.quantity > -1) {
productQuantity = addedItem.quantity;
}
const itemInformation = {
"itemId": itemId,
"selectedStore": selectedStore,
"addedItem": addedItem,
"basketInfo": basketInfo,
"displayValues": null,
"quantity": productQuantity,
"isCustomProduct": false
};
return itemInformation;
}).catch(err => error => reject(error));
} // end of updateCartInfo method