urgent help pls - remove multiple items from cart, how to do wixStores.removeProductFromCart in a loop?

Trying to build store. Our store d

elivery has limit. So if customer has certain items in cart when their postcode is our of our scope, we have to remove those from cart.

I have a list of item ids in ‘removedItems’, I loop through them, and in each loop i call wixStores.removeProductFromCart. As wixStores.removeProductFromCart is a promise call, so when i have more than 2 items to remove, most likely loop finished when removeProductFromCart only completes first 1-2. Result is, some items not removed and remains in cart.

Below I shrink code to skeleton, for easy understanding. I believe it’s quite common for async call (promise) in loop. Question is, how to make sure the async call completes before loop does. Else wise, we are in a totally uncontrollable situation. I really appreciate help from our friendly community.

for (i = 0; i < removedItems.length; i++) {

console.log("doing # "+i);

wixStores.removeProductFromCart(removedItems[i]._id) .then((updatedCart) => {

//nothing

}).catch((error) => {

// Product not removed

console.error(error);

});

}

}

Here is the behavior in web. Right side the lightbox list all ‘removedItems’. We can see on cart page below, there is one left behind, not removed.

Hey, the remove Item from cart function, receives the cart line item id and not the product._id maybe this is the issue.
If you want to remove by productId you had to filter first:

const itemToRemove = currentCart.lineItems.find(lineItem => lineItem.productId = productIdToRemove);



hi Binyamin,
thanks a lot for your reply. my removedItems has been reconstructed for repeater to show, so removedItems[i]._id is cart.lientItem[i].id. _id is same as id. Also you can see from my screen, all the items in the list have been removed succesfully, except one left behind marked in red.
let’s not be distracted by _id or id but focus on the main issue here. async call may fulfill in any time later. When in a loop, the loop completed while the async still has a few not done. That is the loose end.

Hello, I have the same problem. Could you solve it?