Home How to call async await in JS such that after a certain time it fetches again?
Reply: 1

How to call async await in JS such that after a certain time it fetches again?

Hello Universe
1#
Hello Universe Published in 2018-01-10 22:17:04Z

I have an async await as below where I am just fetching some JSON data. It is fetching ok. However, if you look in the console, you will notice that in the JSON data, there is a value finish that is basically a Unix timestamp.

When user's current timestamp gets larger than that Unix timestamp, I need to fetch the JSON data again. Then, I need to check the timestamp again and keep on doing this infinitely. The json data changes as soon as the current time is above the finish timestamp.

How can I do this?

Here is a sample codepen about this https://codepen.io/hellouniverse/pen/XVEBXY?editors=1012

class aClass {
 async getData() {
    try {
        let response = await fetch(
            "https://d2nzqyyfd6k6c7.cloudfront.net/nova-player-history/nova969-current.json"
        );
        let json = await response.json();
        return json;
    } catch (e) {
        console.log("Error!", e);
    }
 }
}

$(document).ready(function() {
    const myClass = new aClass();
      var promise = myClass.getData()
            .then(function(data){
                console.log(data);
            });   
});
Peter
2#
Peter Reply to 2018-01-10 22:50:11Z

This code is do what you asked for, I left /* Put Your DOM update code here*/ where you can put your dom manipulation code.

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// This looks weird because jQuery does not like async code in document ready.
$(() => { (async () => {
    let getData = async () => {
        console.log('getData');
        let response = await fetch(
            "https://d2nzqyyfd6k6c7.cloudfront.net/nova-player-history/nova969-current.json"
        )
        let json = await response.json()
        let tDiff = json.finish - Math.round((new Date()).getTime() / 1000);
        console.log(json)
        console.log(`Refresh in ${tDiff}s`)
        /* Put Your DOM update code here*/

        await sleep(tDiff * 1000)
    }

    // Run It forever
    for (;;) await getData()

})()});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328415 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO