【问题标题】:How can i execute a promise after the endpoint response?端点响应后如何执行承诺?
【发布时间】:2022-01-26 20:29:08
【问题描述】:

我需要在响应已经返回到浏览器之后执行承诺。就我而言,出于性能原因,我只想转换视频并将输出文件保留在操作系统中,而不使用await。例如:

function endPointHandler(req, res) {
  // ... sync stuff ...

  processVideoConvertion(req); // this method will return a promise that needs to be executed after the response.

  return res.json({ message: 'Success' });

}

如上所示,我不需要processVideoConvertion方法的返回值的任何数据,有什么方法可以做到吗?

【问题讨论】:

  • 你所拥有的不会阻塞(尽管如下所述,如果该承诺抛出错误,它不会处理,所以你应该有一个 .catch 挂在那里来处理错误,即使它是只是为了在本地记录它。)但正如所写,它不会在processVideoConvertion 停止并立即返回响应,而无需等待承诺解决或拒绝。

标签: javascript node.js express promise


【解决方案1】:

您可以.then 和.catch 来检查状态,发送响应后进程将在后台运行。

注意:不要使用 async/await,它会等到视频转换完成(过程完成)。

function endPointHandler(req, res) {
  // ... sync stuff ...

  processVideoConvertion(req)
    .then((data) => console.log("Video Converted", data))
    .catch((e) => console.error("Video Conversion Failed", e));

  return res.json({ message: "Success" });
}

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2020-12-23
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多