2

I am working through learnyounode from NodeSchool.

In this problem we are provided with three URLs as the first three command-line arguments. We must collect the complete content provided to us by each of the URLs and print it to the console (stdout). We don't need to print out the length, just the data as a String; one line per URL. The catch is that we must print them out in the same order as the URLs are provided to us as command-line arguments.

Here is my current attempt at a solution, however, there seems to be an issue. The program enters an infinite loop, and I can not figure out why. It appears that the Promise objects in the promiseQueue do not seem to update themselves upon their corresponding response.on('end', ...). Any help would be much appreciated.

var http = require('http');

// Wraps an http GET request.
// Three attributes
//    - data : String
//    - resolved : boolean
//    - error : Error
function Promise(url) {
  this.resolved = false;
  this.error = null;
  this.data = '';

  var self = this;
  http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
      self.data += data;
    });
    response.on('error', function(error) {
      self.error = error;
      self.resolved = true;
    });
    response.on('end', function() {
      self.resolved = true;
    });
  });
}

var urls = process.argv.slice(2);
var promiseQueue = urls.map(function(url) {
  return new Promise(url);
});

var promise;
while (promiseQueue.length) {
  if (promiseQueue[0].resolved) {
    promise = promiseQueue.shift();
    console.log(promise.data);
  }
}

1 Answer 1

2

JavaScript is single-threaded by nature. That is, only one task can be run at a time. When asynchronous operations complete, they queue a task in the event loop that is executed when all other tasks before it have completed.

The while loop you have is blocking all other operations because it runs indefinitely and keeps the thread busy, so no pending tasks can be dequeued. You have to use callbacks and events to work around the problem.

That is why there are no Promise polyfills as small as what you have there ;-).

Sign up to request clarification or add additional context in comments.

1 Comment

Great Answer. Exactly the information I was missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.