我有一个js
函数获取功能,需要获取一些数据,然后我还有其他函数依赖于获取的信息才能使它们工作。结果,我的获取花费了太长时间,因此其他函数给我一个错误,即没有“数据”可供使用的函数。我如何做到这一点,以便在我的任何功能开始工作之前,第一次访存可以收集信息?
console.log("Hello");
fetch("https://api.propublica.org/congress/v1/113/senate/members.json",{
method:"GET",
headers:{
"Content-type": "application/json",
"X-API-Key": "eKDuyBWdpQGhsiKGi7geFoBmJR3kCRIRUGRWIASL"
}
})
.then( (response)=>{
if(response.ok){
return response.json();
}else{
throw new Error('BAD HTTP stuff');
}
})
.then( (data) => {
console.log(data);
})
.catch( (err) =>{
console.log('ERROR: ', err.message);
});
我得到的错误是
“未捕获的ReferenceError:未定义数据”在houAtt.js:1处,然后第一行是:var Members = data.results [0] .members;
[当您依赖使用AJAX
检索的数据时,应等待从promise接收到fetch。
所以,假设您的API函数是
function callAPI(){
return fetch("https://api.propublica.org/congress/v1/113/senate/members.json",{
method:"GET",
headers:{
"Content-type": "application/json",
"X-API-Key": "eKDuyBWdpQGhsiKGi7geFoBmJR3kCRIRUGRWIASL"
}
});
}
此函数将返回HTTP
许诺。
因此,在调用方函数中,您可以捕获数据。
function caller(){
try {
callAPI().then( (response)=>{
if(response.ok){
console.log(response.json());
}else{
throw new Error('BAD HTTP stuff');
}
});
} catch(err) {
console.log('ERROR: ', err.message);
};
}
fetch(..)
.then(response)
.then((data)=>{
//Your function code
});
您是否尝试像这样进行同步?您还能分享有关如何获取以及函数如何依赖响应的更多信息吗?这将有助于回答您的查询