是否可以等到'Fetch'指令完成后再执行下一个代码/指令? (就像AJAX等待的方式一样)
这些功能实际上用于从Facebook Graph API请求帖子的“隐私价值”,但是,如何在“一切”结束之前运行警报提示框(FirstRequestToGraph + RequestNextPage)
FirstRequestToGraph(AccessToken)
.then(function() {
RequestNextPage(NextPage); //recursively until there's no more next page
})
.then(function() {
alert("everything have ended nieely"); //still pop up before RequestNextPage Completed
});
_
function RequestNextPage(NextPage){
fetch(NextPage, {
method: 'GET'
})
.then(function(response) {
return response.json();
})
.then(function(json) {
if(json.data.length == 0 ){
console.log("ended liao lur");
}else{
RequestNextPage(json.paging.next);
}
})
.catch(function(err) {
console.log(`Error: ${err}` )
});
}
_
function FirstRequestToGraph(AccessToken){
fetch('https://graph.facebook.com/v2.8/me?fields=posts.limit(275){privacy}%2Cname&access_token='+AccessToken, {
method: 'GET'
})
.then(function(response) {
return response.json();
})
.then(function(json){
NextPage = json.posts.paging.next;
})
.catch(function(err) {
console.log(`Error: ${err}` )
});
}
答案 0 :(得分:3)
{{1}}
答案 1 :(得分:0)
如果您的组件中有一个异步函数,就像这样...
async getJSON() {
return fetch('/website/MyJsonFile.json')
.then((response)=>response.json())
.then((responseJson)=>{return responseJson});
}
然后您可以使用 await 命令调用它,然后等待其下载,使用类似这样的方法...
render() {
const json = await this.getJSON(); // command waits until completion
console.log(json.hello); // hello is now available
}
您还将希望将getJSON(),return fetch()
更新为return await fetch()
。
async
很棒。 await
也是如此。