gpt4 book ai didi

javascript - 如何在 Fetch API 响应之外访问 JSON 对象?

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:16 24 4
gpt4 key购买 nike

我目前在访问 emoji_map 时遇到问题then之外范围,但我不知道该怎么做。

这是我的代码:

if (req) {
fetch(req).then(function(response) {
return response.json();
}).then(function(response) {
/* start to observe */
emoji_map = response.emoji_map;
console.log(emoji_map);
});

}

当我执行 console.log(emoji_map); 时在 if 循环之外我无法访问分配的响应。有人可以帮忙吗?

最佳答案

我建议您在 MDN 上阅读有关 JavaScript 词法作用域和闭包的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures .

function init() {
var name = "Mozilla"; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();

init() creates a local variable name and then a function called displayName(). displayName() is an inner function that is defined inside init() and is only available within the body of that function. displayName() has no local variables of its own, however it has access to the variables of outer functions and so can use the variable name declared in the parent function.

关于javascript - 如何在 Fetch API 响应之外访问 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41463638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com