Thursday, 16 March 2017

Implementing Chrome-like Asynchronous 'fetch' Node.js

I'm trying to implement a Chrome like fetch function in Node.js using Promises. Here's what I have achieved so far:

var http = require("http");

var options = {
  host: 'eternagame.wikia.com',
  path: '/wiki/EteRNA_Dictionary'
};

const fetchHtml = options => new Promise(

(resolve, reject) =>

    http.get(options, function (http_res) {
        var data = "";
        http_res.on("data", buffer => data += buffer);

        http_res.on("end", function () {
            console.log("fetch complete");
            resolve(data);
        });
    })
)


fetchHtml(options).then(console.log("fetch actually complete"));

The problem is that for some weird reason, "fetch actually complete" is printed first and then "fetch complete" is printed. This should be the other way round, since "fetch actually complete" is wrapped in the then routine of the Promise.

Why is this so? I'm calling the resolve in http_res.on("end",... block. Isn't the then routine started when the promise has resolved?



via Cosmonavt

No comments:

Post a Comment