promiseproxy
v1.0.3
Published
Recursively promisify callback-style APIs based on a simple scheme and Proxy objects
Downloads
6
Maintainers
Readme
Lightweight promisified API wrappers
A yet another library for promisifying callback-style APIs, but this time implemented using the ES2015 Proxy
object. It works by intercepting method calls to the API and returning a promise if a callback parameter was expected.
The benefit of using proxies is that the API is extended without the need to duplicate or mutate the original API implementation. The main functionality of the proxies is implemented in less than 20 lines, making this approach lightweight and easily auditable.
Used in
- promiseproxy-chrome – Promisified Chrome extension API
- promiseproxy-node – Promisified Node.js 6.x API
About Proxy
Requirements
Proxy
requires native ES2015 support since it's not practicable to shim it for ES5 environments. It is supported in Node.js 6+, Chrome, Firefox and Edge.
API
Example
const {PromiseProxy} = require("promiseproxy")
PromiseProxy(target, schema) ⇒ Proxy ⏏
Factory of Proxy
objects for recursively promisifying a callback-based API
Kind: global method of promiseproxy
| Param | Type | Description | | --- | --- | --- | | target | Object | The API to be promisifed | | schema | Object | API structure with callback parameter position |
Example
// Define chrome.tabs.query(_, callback) and .update(_, _, callback) methods
// 1 and 2 are the positions of the callback parameters (zero-based)
const schema = {tabs: {query: 1, update: 2}}
// Promisify the Chrome API based on the schema
const _chrome = PromiseProxy(chrome, schema)
// The promisified methods return a Promise if the callback parameter is omitted
_chrome.tabs.query(info).then(callback)
// The same methods can still be used with a callback
_chrome.tabs.query(info, callback)