我的许多脚本都取决于使用 fetch()
和 .json()
从.json文件中读取的信息,因此它是异步的。我需要将其余脚本的执行延迟到这些功能完成,而不会将其余的代码粘贴在巨大的.then()
或功能块或其他方面。我已经四处搜索,但我真的找不到我要寻找的东西。
let config;
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(json => config = json);
console.log(config);
// REST OF SCRIPT
它应该记录config json对象或承诺,但显然,它只返回未定义。任何帮助将不胜感激!
在请求返回之前,您的 config
正在读取。您可以添加另一个then
子句:
let config;
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(json => config = json)
.then(() => {
console.log(config);
});
您只有一个线程可以使用,因此您无需执行config和的异步提取,然后 继续您的计划的其余部分。大多数JavaScript都是事件驱动的,因此这通常不是一个大问题。您可以以代码的主要入口为 main()
函数的样式编写,然后您可以在获取config时将其调用:
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(main);
function main(config){
// do stuff
}
无论如何,任何基本大的代码库都会被重构为较小的功能,因此理想情况下,您的main
功能不应该真正大。
您可以使用以下方式:
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(config => console.log(config));
或:
const response = await fetch(chrome.runtime.getURL("../config.json"));
const config = await response.json();
config => console.log(config)