首页 > 解决方案 > 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
});

标签: javascriptnode.jspromisecallback

解决方案


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.)


推荐阅读