I need to capture the cartID in a js variable from a JSON response.
So far I have the following code which requests the cart information.
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
The console.log data is formatted like this:
Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me@gmail.com", ................. }]
I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.
Any ideas how to delay until the response is ready and then 'cartID' with the id value?