如何正确创建在调用Webhook时解决的承诺
我刚刚观看了詹姆斯·斯内尔(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论