javascript - Convert Callback to Promise in Publish Subscribe Model
问题描述
Let say we have a service called A
and it has the function subscribe(callback)
. The subscription from the service is an open connection that can receive data at any time, and the data can be accessed through the callback.
Can we convert this callback to promise? if so, how?
Sample
A.subscribe((error, data) => {
// do something with data
});
解决方案
Can we convert this callback to promise?
Not just one promise, no, because a promise can only be settled once, with a single fulfillment value (on success), but you have a series of values (often called an "observable"). So you can't convert that to return a promise, unless of course you want the promise to only fulfill with just one of the values (the first, for instance).
You could convert it to an asynchronous iterator (perhaps using an async
generator function). As the name implies, an asynchronous iterator provides a series of values asynchronously, by returning a series of promises. I can't say whether an asynchronous iterator is applicable to your use case, but it's the closest thing to a promise-based observable that comes to mind.
Here's an observable-to-async-iterator implementation designed for Angular's observables, but which could be adapted as necessary. (Sadly, there's no license indicated, so I can't copy it into the answer.)
推荐阅读
- python - Python3:如何根据条件拆分列表?
- flutter - 带有资产图像和文本的卡片
- sql - 查询以按值并排获取总不同值
- javascript - 如何让我的汉堡菜单响应式?
- java - 如何将 TextureAtlas 用于动画而不是 TextureRegion?-libgdx
- sql - 如何读取 DataBaseRoom 并显示 textView
- visual-studio-code - VSCode 中的 Ctrl+shift+箭头不会选择整个单词
- azure-ad-b2c - Azure B2C 中的 KMSI 实际上有什么作用?
- c - 警告 C6386:写入数据时缓冲区溢出 (c) 在 0x00F622D9 处引发异常
- javascript - 如何增加/减少在固定容器内滚动的元素的不透明度