【问题标题】:Response terminates before the result could be collected from the promise在可以从 Promise 中收集结果之前响应终止
【发布时间】:2017-08-12 04:06:13
【问题描述】:

在下面的 sn-p 中,lineReader 监听事件 line。当收到line 事件时,它会在Parser 上调用da,这会返回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 函数返回调用一个同样作用于Promise 的函数。发生的情况是我永远看不到 geo.getLocationreadLine.on('close') 的输出被调用。

应该如何处理这种情况?

【问题讨论】:

  • 避免使用Promise constructor antipattern! (但这不应该阻止你的日志)
  • 也许getLocation 承诺被拒绝了?你没有在任何地方处理错误。
  • 无论您做什么,都会触发关闭事件,readline 流不关心(并等待)您在 line 处理程序中执行的操作

标签: javascript node.js promise


【解决方案1】:

你没有解决承诺。当您从地理服务获得结果时,您需要解析数据。

看看这个

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

【讨论】:

  • 它正在解决,但流量从未到达那里。请查看编辑。
  • 我刚刚看到您的编辑。 BTW,不用退货,解决就好。
【解决方案2】:

为什么你不只是从 geo.geoLocation() 返回 Promise 而不是将它包装到另一个 Promise 中?像这样:

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

或者您可能想要链接“then”。虽然这是同步的

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

一个可能的问题是 promise 是异步的,所以 lineReader.on("line");因为事件是同步的,所以在 Promise 可以执行之前关闭事件。然后是 lineReader.on("close");在 promise 解决之前执行。

此外,您的承诺中应该始终有一个“catch”,这样您就可以查看是否有任何错误。像这样:

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

【讨论】:

    猜你喜欢
    • 2014-04-05
    • 2017-08-26
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2022-08-12
    • 1970-01-01
    • 2015-02-11
    相关资源
    最近更新 更多