Is it possible to wait until the fetch
instruction has completed before executing the next code / instruction (just like how AJAX waiting works)?
These functions are actually used to request the “privacy value” of a post from the Facebook Graph API. How can I keep an alert box from running until everything is over (i.e. the chained fetching in FirstRequestToGraph
and RequestNextPage
)?
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}`)
});
}
FirstRequestToGraph(AccessToken)
.then(function() {
RequestNextPage(NextPage); // Recursively until there's no more next page.
})
.then(function() {
alert("everything has ended nicely"); // Still pop up before `RequestNextPage` completed.
});
FetchRequest
you need toreturn fetch ...
- and inRunFetchRequest
you need toFetchRquest().then(function(result) { ... this code runs after fetch finishes });
– Kinfolkjust like how AJAX waiting works
- you must be doing AJAX wrong ... the first A in AJAX meansasynchronous
... which is what you're having issues with in the code above, the asynchronous nature of fetch and AJAX in general – Kinfolkreturn fetch ...
inFirstRequestToGraph
- then you can useFirstRequestToGraph().then(...)
– Kinfolkfetch(
at the TOP of the function ... put areturn
before the wordfetch
– Kinfolk