У меня есть страница продуктов с кнопкой (addToCart
), и я использую fetch, чтобы добавить продукт в req.session.cart
на сервере. В передней части приложения я использую fetch для связи с сервером и получаю req.session.cart
в качестве возвращаемого значения. Как назначить результаты выборки внешней переменной?
let whatevervariablehere
function addToCart(e){
let items = e.target.parentElement.parentElement
// rest of the clicked item code .....
//fetch and send the data to server so you can update session
fetch('sc8', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
title : title,
price : price,
description : description,
id : id
})
}).then(response => response.json()).then((results) => {
//**this is the part I'm talking about**
console.log("|||||results|||||", results)
//**How to get access to "retrievelocalstorage" from outside of this code**
localstorage = window.localStorage.setItem(JSON.stringify(user), JSON.stringify(results));
retrievelocalstorage = JSON.parse(window.localStorage.getItem(JSON.stringify(user))) || "No items in cart, Yet!";
// the below console.log prints the right results
console.log("retrievelocalstorage", retrievelocalstorage)
}) //results function end
.catch(error => console.log(error));
} //end of addTocart Function
// this prints "outside the addToCart" and nothing else.
// it is outside the addToCart fn and the fetch promise.
// can I have access to retrievelocalstorage value out here, out of the
// function and the promise or not?
**console.log("this is outside the addToCart fn", retrievelocalstorage)**
Можно ли получить доступ к retrievelocalstorage
вне результатов fn?
Edit 1 Console.log («это за пределами функции addToCart», retrievelocalstorage) не выводит значение retrievelocalstorage. поэтому предложение добавить .then (retrievelocalstorage => anyvariablehere = retrievelocalstorage) по-прежнему показывает любую пустую переменную в consolelog.