我有一个产品页面,上面有一个按钮(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?
编辑1console.log("this is outside the addToCart fn", retrievelocalstorage)并没有打印retrievelocalstorage的值,所以建议添加.then(retrievelocalstorage => whatevervariablehere = retrievelocalstorage)在consolelog中仍然显示whatevervariable为空。
你可以尝试在这里使用asyncawait,这样你就不会使用了。.then
并可以将结果分配给一个变量。
async function getResults() {
const result = await fetch(...).json() // your code for fetch
// work with result as a regular variable
}
你是在async上下文中。你应该继续在承诺里面工作。
.then(() => {
// you can get your data from LocalStorage here
})
后面的代码 fetch
不劳而获
或者你可以将异步 fn 封装到另一个 fn 中,然后使用 async/await
async function() {
await addToCart...
// you can get your data from LocalStorage here
}