When I have two methods shoppingCartPlaceOrder() and shoppingCartSetOrderLineItem(). I need wait when shoppingCartPlaceOrder() ends and get Id of order from this method. Then it's needed to execute shoppingCartSetOrderLineItem() and use that Id. There is an catch in handlePlaceOrder(): 'this.shoppingCartPlaceOrder(): error'.
Here is simplified code:
import { LightningElement } from 'lwc';
export default class ShoppingCart extends LightningElement {
nameOfOrderFromCart;
sumOfPricesFromCart = 0;
orderId;
lineItemsIds;
shoppingCartPlaceOrder() {
return new Promise(function(resolve, reject) {
placeOrder({
nameOfOrder : this.nameOfOrderFromCart,
price : this.sumOfPricesFromCart
})
.then( result => {
resolve('resolve: It\'s written. Order Id: ' + result);
this.orderId = result; // add Id of order in database
})
.catch(error => {
reject('reject: Error writing order.');
debugger;
});
});
}
shoppingCartSetOrderLineItem() {
setOrderLineItem({
orderId : this.orderId, // Id from shoppingCartPlaceOrder() -> placeOrder()
line : 1;
})
.then( result => {
this.lineItemsIds = result; // add actual Id of order line item in database
})
.catch(error => {
debugger;
});
}
handlePlaceOrder() {
// waiting for Order Id
this.shoppingCartPlaceOrder()
.then(function(result) {
console.log('this.shoppingCartPlaceOrder(): success'); // => I would like executed this line
})
.catch(function(error) {
console.log('this.shoppingCartPlaceOrder(): error'); // => this line is executed, why?
})
this.shoppingCartSetOrderLineItem();
}
Does new Promise is wrong in method shoppingCartPlaceOrder()? How to do it, that first will be executed this.shoppingCartPlaceOrder() and when it ends, then will be executed this.shoppingCartSetOrderLineItem()?