如何在利用 .fetch 和 Promise 的函数之外使用对象?
如果我有:
getBuildList();
function getBuildList(){
fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
.then(function(res){
return res.json();
})
.then(function(data) {
initialLoad(data);
})
.catch(function(err){
console.log(err);
});
}
我想在此函数范围之外使用data
。
我尝试在该函数内的几乎所有位置添加返回数据
,但似乎无法使其在此函数范围之外可用。
理想情况下,我只想从 API 获取此数据一次,然后在 DOM 上按下按钮时通过不同的功能重新使用获取的数据。
我已经尝试过(以及其他许多尝试):
getBuildList();
let jsonData = getBuildList();
console.log(jsonData); //expecting data from fetch. but returns undefined
function getBuildList(){
fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
.then(function(res){
return res.json();
})
.then(function(data) {
initialLoad(data);
let myData = data;
return myData;
})
.catch(function(err){
console.log(err);
});
}
最佳答案
只需返回 promise :
function getBuildList(){
// (note the "return" below, otherwise result will be undefined.
return fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
.then(function(res){
return res.json();
})
.then(function(data) {
initialLoad(data);
let myData = data;
return myData;
})
.catch(function(err){
console.log(err);
});
}
然后使用 .then 使用结果:
getBuildList().then(function(jsonData){
// use jsonData here.
}).catch(function(error){
// Handle the error here.
});
编辑:要将结果存储在全局变量中,请编辑最后一段代码,如下所示:
var jsonData = null; // <-- global variable
getBuildList().then(function(res){
jsonData = res;
}).catch(function(error){
// Handle the error here.
});
点击消耗数据的示例(确保调用上述函数后)
function consumeData() {
if (jsonData) { // <-- this will assert jsonData is truthy, meaning it's not null or undefined, in that case.
// consume jsonData here. Remember that changing jsonData will change it GLOBALLY!.
}
else {
// OOOPS, jsonData may either be not yet defined or may just be null or empty due to a misleading or wrong fetch response.
}
}
关于javascript - 在函数/promise 范围之外使用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590337/