jon*_*ona 7 javascript fetch-api
是否可以等到“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
});
Run Code Online (Sandbox Code Playgroud)
_
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}` )
});
}
Run Code Online (Sandbox Code Playgroud)
_
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}` )
});
}
Run Code Online (Sandbox Code Playgroud)
Hol*_*ger 36
如果你的组件中有一个异步函数,就像这样......
async getJSON() {
return fetch('/website/MyJsonFile.json')
.then((response)=>response.json())
.then((responseJson)=>{return responseJson});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以调用它,并等待它下载,使用await命令,使用类似这样的东西......
async caller() {
const json = await this.getJSON(); // command waits until completion
console.log(json.hello); // hello is now available
}
Run Code Online (Sandbox Code Playgroud)
您还需要将 getJSON() 更新return fetch()
为return await fetch()
.
async
太棒了。亦是如此await
。
FirstRequestToGraph(AccessToken).then(function() {
alert('testing1234');
});
function RequestNextPage(NextPage) {
return fetch(NextPage, {
method: 'GET'
})
.then(function(response) {
return response.json();
})
.then(function(json) {
RequestNextPage(json.paging.next);
})
.catch(function(err) {
console.log(`Error: ${err}`)
});
}
function FirstRequestToGraph(AccessToken) {
return 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) {
if(json.data.length !== 0 ){
return RequestNextPage(json.paging.next);
}
})
.catch(function(err) {
console.log(`Error: ${err}`)
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33560 次 |
最近记录: |