[英]How do I save the data I get from a fetch request in JavaScript into a variable that is external to my function
Obvsiouly I'm very new to Javascript.显然我对 Javascript 很陌生。 For an app that I'm building, I need to save the data I get from a fetch request into a variable that ideally I can access outside of my function.
对于我正在构建的应用程序,我需要将从获取请求中获得的数据保存到一个变量中,理想情况下我可以在 function 之外访问该变量。 Any light on this would be hugely appreciated.
对此的任何启示将不胜感激。
Here's my code:这是我的代码:
function generateNewQuote() {
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
.then(response => response.json())
.then(data => {
const newMes = data.message;
console.log(newMes );
});
}
I need to get the value of my newMes variable into a variable that I can specify in the global scope or alternative a way to access the newMes variable locate inside my generateNewQuote function in the Global Scope.我需要将我的 newMes 变量的值转换为我可以在全局 scope 中指定的变量,或者访问位于全局 Z5D113F2038D289F29E861 中的 generateNewQuote function 中的 newMes 变量的方法。
Change the variable Scope.更改变量 Scope。
let newMes = [];
function generateNewQuote() {
newMes = [];
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
.then(response => response.json())
.then(data => {
newMes = data;
console.log(newMes.message );
});
}
This may not be the most right answer, but this works.这可能不是最正确的答案,但这是可行的。 As setTimeout also works somewhat like await outside an async function.
因为 setTimeout 也有点像在异步 function 之外等待。
var newMes;
function generateNewQuote() {
fetch('https://api.whatdoestrumpthink.com/api/v1/quotes/random')
.then(response => response.json())
.then(data => {
newMes = data.message;
// console.log(newMes);
});
}
generateNewQuote();
setTimeout(function() {console.log(newMes)}, 2000)
The code above basically waits for a while before putting newMes into the console.上面的代码在将 newMes 放入控制台之前基本上要等待一段时间。 Because the problem of newMes being undefined is that the script is still fetching data from the server and thus requires a bit of time.
因为 newMes 未定义的问题是脚本仍在从服务器获取数据,因此需要一些时间。
The problem of this is that 2000 milliseconds may not be enough to load the data and thus console.log(newMes) will return undefined.问题在于 2000 毫秒可能不足以加载数据,因此 console.log(newMes) 将返回 undefined。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.