如何正确创建在调用Webhook时解决的承诺

发布于 2025-02-09 14:53:05 字数 1157 浏览 1 评论 0原文

我刚刚观看了詹姆斯·斯内尔(James Snell)在节点中对承诺的出色演讲: https://www.youtube。 com/watch?v = xv-u_ow47s0

这让我想到了一个我的代码,我调用了Web服务,提供Webhook URL,我敢肯定这是次优的。但是我不知道该如何正确编写。为了解释我的代码:

const activeRequests = new Map();

function makeRequest(id:string) {
  return new Promise(resolve => {
    fetch(`http://external.com/someComplexCalculation`,
      { 
        method:"POST",
        body: { webhook:`http://myservice.com/webhook/${id}` }
      })
    .then(res => {
      activeRequests.set(id, resolve);
    });
  });
}

expressApp.post('/webhook/:id', (req, res) => {
  const active = activeRequests.get(req.params.id);
  if (active) {
    active();
  }
  res.sendStatus(200);
});

我已经跳过了所有错误处理以清楚的问题,但是您明白了。这是这样做的最好方法吗?最终目标是让makErequest的呼叫者接收到webhook时可以解决的承诺。

预期的流是我的应用程序调用等待Makerequest(xx)调用某些外部服务 - 然后,该服务然后通过/webhook/xx url回电给我的应用程序是通过其处理完成的,此时原始的Makerequest Promise解决了。

我当前在地图中存储了从新承诺中存储resolve函数实现这不涉及这种奇怪的安排?

I just watched James Snell's excellent talk on Promises in Node: https://www.youtube.com/watch?v=XV-u_Ow47s0

This got me thinking about a piece of code I have that calls a web service, supplying a webhook URL, which I'm sure is suboptimal. But I don't know how I should write this correctly. To paraphrase my code:

const activeRequests = new Map();

function makeRequest(id:string) {
  return new Promise(resolve => {
    fetch(`http://external.com/someComplexCalculation`,
      { 
        method:"POST",
        body: { webhook:`http://myservice.com/webhook/${id}` }
      })
    .then(res => {
      activeRequests.set(id, resolve);
    });
  });
}

expressApp.post('/webhook/:id', (req, res) => {
  const active = activeRequests.get(req.params.id);
  if (active) {
    active();
  }
  res.sendStatus(200);
});

I've skipped all the error handling for clarity, but you get the idea. Is this the best way to do this? The end goal is for the caller of makeRequest to receive a promise that will resolve when the webhook is called.

The expected flow is that my application calls await makeRequest(xx) which calls some external service - that service then calls back to my application via the /webhook/xx URL when it is done with its processing, at which point the original makeRequest promise resolves.

I currently store the resolve function from the new Promise in a Map since I can't call that resolve function until the webhook is invoked, but that is the crux of my question: is there a better way to achieve this that doesn't involve this odd arrangement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文