как получить доступ к переменным внутри возвращаемого значения Fetch - PullRequest
0 голосов
/ 07 мая 2020

У меня есть страница продуктов с кнопкой (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.

Ответы [ 2 ]

1 голос
/ 07 мая 2020

Вы можете попробовать использовать здесь async / await, чтобы не использовать .then и присвоить результат переменной.

async function getResults() {
  const result = await fetch(...).json() // your code for fetch
  // work with result as a regular variable
}

1 голос
/ 07 мая 2020

Вы находитесь в контексте asyn c. Вы должны продолжить работу внутри обещания:

.then(() => {
   // you can get your data from LocalStorage here
})

Код после fetch работает без ожидания результатов

Или вы можете перенести asyn c fn в другой fn и использовать async/await

async function() {
  await addToCart...
  // you can get your data from LocalStorage here
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...