3 回答

TA贡献1780条经验 获得超5个赞
您只有一个线程可以使用,因此您需要执行配置的异步获取,然后继续执行程序的其余部分这一事实是无法回避的。大多数 javascript 是事件驱动的,所以这通常不是一个大问题。您可以编写代码的主要入口是一个main()函数的样式,然后您可以在获取它后使用配置调用它:
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(main);
function main(config){
// do stuff
}
无论如何,任何相当大的代码库都将被重构为更小的函数,因此理想情况下,您的main函数一开始就不应该那么大。

TA贡献1793条经验 获得超6个赞
config在请求返回之前您正在被读取。您可以添加另一个then子句:
let config;
fetch(chrome.runtime.getURL("../config.json"))
.then(response => response.json())
.then(json => config = json)
.then(() => {
console.log(config);
});

TA贡献1735条经验 获得超5个赞
你可以使用这个:
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)
添加回答
举报