23

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.
  });
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
jona
  • 592
  • 1
  • 4
  • 16
  • 4
    yes and no ... in `FetchRequest` you need to `return fetch ...` - and in `RunFetchRequest` you need to `FetchRquest().then(function(result) { ... this code runs after fetch finishes });` – Jaromanda X Jan 21 '17 at 03:45
  • 1
    `just like how AJAX waiting works` - you must be doing AJAX wrong ... the first A in AJAX means `asynchronous` ... which is what you're having issues with in the code above, the asynchronous nature of fetch and AJAX in general – Jaromanda X Jan 21 '17 at 03:47
  • hello, sorry to interrupt, i have tried using .then to waits for the current fetch request to complete and then execute the next, however, i don't think it works in my case as i'm not really sure 'the way i chained' the fetch request is correct or not. (i have edited the codes on my question) – jona Jan 21 '17 at 05:48
  • doing something like this doesn't help me to solve any problem at all :( FirstRequestToGraph(AccessToken).then(function(){ console.log('haha'); }); – jona Jan 21 '17 at 05:59
  • as I said in the first comment ... you need to `return fetch ...` in `FirstRequestToGraph` - then you can use `FirstRequestToGraph().then(...)` – Jaromanda X Jan 21 '17 at 06:05
  • sorry :( i don't really understand what do i return in FirstRequestToGraph <"return fetch ... "> – jona Jan 21 '17 at 06:36
  • put the word return before the word fetch ... that way you return the promise chain – Jaromanda X Jan 21 '17 at 06:36
  • thank you, i finally understand what you meant by completing the promise chain (return fetch), but however, my codes still aren't working as expected, alert(testing1234) still unable to be prompt – jona Jan 21 '17 at 06:52
  • no no no, oh dear god no, see the `fetch(` at the TOP of the function ... put a `return` before the word `fetch` – Jaromanda X Jan 21 '17 at 07:03

2 Answers2

33

If you have an asynchronous function in your component, like this...

async getJSON() {
    return fetch('/website/MyJsonFile.json')
        .then((response)=>response.json())
        .then((responseJson)=>{return responseJson});
}

Then you can call it, and wait for it download, with the await command, using something like this...

async caller() {
    const json = await this.getJSON();  // command waits until completion
    console.log(json.hello);            // hello is now available
}

You'll also want to update getJSON(), return fetch() to return await fetch().

async is wonderful. So is await.

Check it out: Mozilla Developer Network: Async Function

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
5
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}`)
    });
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • 1
    hello again, thank you very very very much for helping :)) i am not sure what causes my codes not to works, the alert prompt box still pop up before the previous function ended (.then works perfectly already) – jona Jan 21 '17 at 08:35
  • Sorry, I missed another return ... `return RequestNextPage(NextPage);` ... I've now changed the answer to be similar the code you edited after I posted the answer :p – Jaromanda X Jan 21 '17 at 08:55
  • thank you very very much!!!! appreciate it a lot! *sudden realization, and understand all the return stuff.... <3 – jona Jan 21 '17 at 09:17