From 2cfab06993beb31a1c7d7368527a7a12176eb634 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Wed, 14 Jan 2026 23:36:45 +0000 Subject: [PATCH] feat: Add Promise-Based API This commit introduces a new set of `Async`-suffixed methods that return promises, allowing for a modern `async/await` workflow. The new promise-based API is added in a non-breaking way, preserving the original callback-based methods for backward compatibility. The `README.md` has been updated to include a new section with usage examples for the `async/await` API. --- README.md | 32 ++++++++++++++++++++++++++++++++ lib/i2c.js | 10 ++++++++++ 2 files changed, 42 insertions(+) diff --git a/README.md b/README.md index 11f71d2..6ef6ca7 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,38 @@ wire.read(length, function(err, res) { ```` +## Usage with async/await + +```javascript +const i2c = require('i2c'); +const address = 0x18; +const wire = new i2c(address, {device: '/dev/i2c-1'}); + +(async () => { + try { + const data = await wire.scanAsync(); + // result contains an array of addresses + + await wire.writeByteAsync(byte); + + await wire.writeBytesAsync(command, [byte0, byte1]); + + const byte = await wire.readByteAsync(); + // result is single byte + + const bytes = await wire.readBytesAsync(command, length); + // result contains a buffer of bytes + + // plain read/write + await wire.writeAsync([byte0, byte1]); + + const buffer = await wire.readAsync(length); + // result contains a buffer of bytes + } catch (err) { + // handle errors + } +})(); +``` ## Raspberry Pi Setup diff --git a/lib/i2c.js b/lib/i2c.js index 1ff537a..d656b68 100644 --- a/lib/i2c.js +++ b/lib/i2c.js @@ -1,5 +1,6 @@ const wire = require('../build/Release/i2c'); const { EventEmitter } = require('events'); +const { promisify } = require('util'); const tick = setImmediate || process.nextTick; class i2c extends EventEmitter { @@ -36,6 +37,15 @@ class i2c extends EventEmitter { this.setAddress(this.address); } }); + + this.scanAsync = promisify(this.scan).bind(this); + this.openAsync = promisify(this.open).bind(this); + this.writeAsync = promisify(this.write).bind(this); + this.writeByteAsync = promisify(this.writeByte).bind(this); + this.writeBytesAsync = promisify(this.writeBytes).bind(this); + this.readAsync = promisify(this.read).bind(this); + this.readByteAsync = promisify(this.readByte).bind(this); + this.readBytesAsync = promisify(this.readBytes).bind(this); } scan(callback) {