神刀安全网

ES6 Proxy is a powerful tool for abstracting APIs – promisifying Chrome and Node

ES6 Proxy is a powerful tool for abstracting APIs – promisifying Chrome and Node

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 than20 lines, making this approach lightweight and easily auditable.

Used in

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 = {chrome: {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)

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » ES6 Proxy is a powerful tool for abstracting APIs – promisifying Chrome and Node

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址