2

In the following snippet, lineReader listens to an event line. When a line event is received, it calls da on Parser which returns a Promise

lineReader.on('line',(line) => {
  Parser.da(line).then((info) => {
  });
});

lineReader.on('close',() => {
  req.end();
});

Parser.da = function(line) {
  return new Promise((resolve,reject) => {
       geo.getLocation().then((r) => {
           console.log(r); return resolve(r);
       }); 
  });
}

da function in return calls a function which also operates on Promise. What happens is that I can never see the output from geo.getLocation and readLine.on('close') gets called.

What should be the way to handle this situation?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! (This should not prevent your log though) – Bergi Mar 20 '17 at 19:11
  • Maybe the `getLocation` promise is rejected? You're not handling errors anywhere. – Bergi Mar 20 '17 at 19:11
  • The close event gets fired regardless of what you do, the readline stream does not care (and wait for) what you do in your `line` handler – Bergi Mar 20 '17 at 19:12

2 Answers2

0

You are not resolving the promise. When you get the result from geo service you need to resolve the data.

Take a look this

Parser.da = function(line) {
  return new Promise((resolve,reject) => {
       geo.getLocation().then((r) => {
           console.log(r);
           resolve(r);
       }); 
  });
}
0

Why do you not just return the Promise from geo.geoLocation() instead of wrapping it into another promise? Like this:

Parser.da = function(line) {
  return geo.geoLocation();
}

Or you might want to chain "then"'s instead. Although this is synchronous

Parser.da = function(line) {
  return geo.geoLocation().then(function (r) {
    console.log(r);
    return r; // return r to chain it to the next ".then"
  });
}

One possible problem might be that a promise is asynchronous so the lineReader.on("line"); event is closed before the promise can be executed because the event is synchronous. And then the lineReader.on("close"); is executed before the promise is resolved.

Also you should always have a "catch" in your promise so you can see if there are any errors. Like this:

lineReader.on('line',(line) => {
  Parser.da(line).then((info) => {
    // ...do code here
  }, console.error); // errors will be outputted to console
});
iFaxity
  • 11
  • 4