11

Is it possible to wait until the 'Fetch' instruction to complete before executing the next code/instruction?? (just like how AJAX waiting works)

These function are actually use to request 'privacy value' of post from Facebook Graph API, however, how can i run alert prompt box until "EVERYTHING" is over (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}` )
  });

}
jona
  • 387
  • 1
  • 3
  • 14
  • 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 – 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

12

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
  • 15,349
  • 8
  • 79
  • 115
4
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
  • 1
  • 4
  • 64
  • 78
  • 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