Asynchronous JavaScript to fetch remote JSON data with promises and generators I am trying to figure out how to do async calls using promises and generators (without 3rd party libraries). Most of the examples I found on the Internet are either incomplete or confusing (at least to me), so I decided to try and write the code myself.

I would really appreciate it if someone could review the code and provide comments and suggestions for improving it.

function getJSON(url) {
    return new Promise((resolve, reject) =&gt; {
        const https = require("https");
        try {
            https.get(url, (response) =&gt; {
                let data = "";
                response.on("data", (part) =&gt; {
                    data += part;
                });
                response.on("end", () =&gt; {
                    try {
                        resolve(JSON.parse(data));
                    }
                    catch(e) {
                        reject("Error parsing data");
                    }
                });
            }).on("error", () =&gt; {
                reject("Error downloading data");
            });
        }
        catch(e) {
            reject("Error: " + e.message);
        }
    });
}

function request(generator) {
    var iterator = generator();
    function process(result) {
        if (result.done) {
            return;
        }
        const value = result.value;
        if (value instanceof Promise) {
            value.then(
                (data) =&gt; {
                    console.log(data);
                    process(iterator.next());
                }
            )
            .catch(
                err =&gt; {
                    iterator.throw(err);
                }
            );
        }
    }
    try {
        process(iterator.next());
    } 
    catch(e) {
        iterator.throw(e);
    }
}

function *DataGenerator() {
    try {
        yield getJSON("https://jsonplaceholder.typicode.com/posts/1");
        yield getJSON("https://jsonplaceholder.typicode.com/posts/2");
        // yield getJSON("https://jsonplaceholder.typicode.com/"); // Parsing error
        // yield getJSON(""); // Domain name error
    }
    catch (e) {
        console.log(e);
    }
}

// Run

console.log("Before");
request(DataGenerator);
console.log("After");


This is also available as a repo.
Why do not use async / await functions? Its just syntactic sugar for promises / generators. Check this vanilla JS snippet, is live:



var url1 = 'https://jsonplaceholder.typicode.com/posts/2'
var url2 = 'https://jsonplaceholder.typicode.com/posts/3'

async function mimicSyncInside () {
  console.log('Before')
  console.log(await fetch(url1).then(resp =&gt; resp.json()))
  console.log(await fetch(url2).then(resp =&gt; resp.json()))
  console.log('After')
}

mimicSyncInside()