0

I have a function that returns a promise. In the first block of the promise, I fetch some XML and write it to a file called feed.xml. Then, in the next block, I convert that XML into JSON. The problem here is that my function tries to convert the xml file to JSON before the file is finished writing to my system. How can I make the second block wait on the first block?

Here is my function:

var out = fs.createWriteStream('./feed.xml');

var fetchJSON = () => {
  return new Promise((resolve, reject) => {

    var feedURL = 'http://www2.jobs2careers.com/feed.php?id=1237-2595&c=1&pass=HeahE0W1ecAkkF0l';
    request(feedURL).pipe(zlib.createGunzip()).pipe(out);
    resolve();

  }).then(() => {

    fs.readFile('feed.xml', function(err, data) {
      parser.parseString(data, function(err, result) {
        console.log(result);
      });
    });

  });
};

fetchJSON();
1
  • You should resolve(request(feedURL).pipe(zlib.createGunzip()).pipe(out)); Commented Nov 18, 2016 at 0:57

1 Answer 1

3

You're resolving before your request has completed.

request(feedURL).pipe(zlib.createGunzip()).pipe(out);
resolve();

You should resolve once the stream has completed, not right after creating it. You can listen on the stream finish event https://nodejs.org/api/stream.html#stream_event_finish

var stream = request(feedURL).pipe(zlib.createGunzip()).pipe(out);

stream.on('finish', function() {
  resolve();
});

This means your promise won't be resolved until the stream has completed.

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

4 Comments

Ok I tried this method and I'm still logging undefined to the console in the "then" block. I checked to make sure my xml called feed.xml contains data and it does. Please have a look at my edited code to see the xml file I'm referencing. Something is going wrong along the way.
Perhaps a better option is to pass the data through the resolution of the promise rather than writing it to a file. Unless you really need the file.
Ok, I tried setting the resultant data to a variable called xml like this: var feedURL = 'www2.jobs2careers.com/…'; var xml = request(feedURL).pipe(zlib.createGunzip()); I console.logged xml and it is a gunZip file, not xml. I'm still a bit confused about this.
Since you're using request you may as well just pass in the { gzip: true } option and let it decompress for you github.com/request/request

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.