下面是我的代码。我想将获取的JSON数据存储在函数范围之外的变量中。我怎样才能做到这一点?
另外,如果我想对获取的JSON数据运行某些功能,是否应该在.then()
内执行这些功能?
let jsondata;
fetch('https://api.myjson.com/bins/wa759')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
jsondata = myJson;
});
console.log("test");
console.log(jsondata);
此日志
> Hello (corresponding to `console.log("test");`)
> undefined (corresponding to `console.log(jsondata);`)
> (the entire JSON data)