Waiting for the fetch to complete and then execute the next instruction
Asked Answered
T

2

28

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.
  });
Tonnie answered 21/1, 2017 at 3:43 Comment(9)
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 });Kinfolk
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 generalKinfolk
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)Tonnie
doing something like this doesn't help me to solve any problem at all :( FirstRequestToGraph(AccessToken).then(function(){ console.log('haha'); });Tonnie
as I said in the first comment ... you need to return fetch ... in FirstRequestToGraph - then you can use FirstRequestToGraph().then(...)Kinfolk
sorry :( i don't really understand what do i return in FirstRequestToGraph <"return fetch ... ">Tonnie
put the word return before the word fetch ... that way you return the promise chainKinfolk
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 promptTonnie
no no no, oh dear god no, see the fetch( at the TOP of the function ... put a return before the word fetchKinfolk
K
7
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}`)
    });
}
Kinfolk answered 21/1, 2017 at 7:11 Comment(3)
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)Tonnie
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 :pKinfolk
thank you very very much!!!! appreciate it a lot! *sudden realization, and understand all the return stuff.... <3Tonnie
I
38

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

Insinuate answered 23/8, 2018 at 19:8 Comment(2)
can you explain the "this" keyword inside the async function? why not just "getJSON()"?Cirsoid
@Cirsoid this means the current object. (Notice how the functions are defined, sans function or =>{}.)Insinuate
K
7
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}`)
    });
}
Kinfolk answered 21/1, 2017 at 7:11 Comment(3)
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)Tonnie
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 :pKinfolk
thank you very very much!!!! appreciate it a lot! *sudden realization, and understand all the return stuff.... <3Tonnie

© 2022 - 2024 — McMap. All rights reserved.