withspectrum/callback-to-async-iterator

Name: callback-to-async-iterator

Owner: Spectrum

Description: Turn any callback-based listener into an async iterator.

Created: 2018-03-09 10:36:24.0

Updated: 2018-05-04 12:35:35.0

Pushed: 2018-03-17 10:49:17.0

Homepage: null

Size: 69

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

callback-to-async-iterator

Turn any callback-based listener into an async iterator.

We needed this module to turn our database listeners into async iterators, which is what GraphQL subscriptions expect to be passed. It might be useful for you too!

install callback-to-async-iterator
Usage

Imagine a standard callback-based listener like this:

allback will be called with each new message added to the database
t listenToNewMessages = (callback) => {
turn db.messages.listen(message => callback(message));

The problem is that callbacks are push based, they push values to the listener whenever a new value is availabe. Async Iterators on the other hand are pull based, they request a new value and wait until it is available.

This module reconciliates that difference so you can turn your standard callback-based listener into an async iterator:

rt asyncify from 'callback-to-async-iterator';

t messages = asyncify(listenToNewMessages);

ait until the first message is sent
t firstMessage = await messages.next();

synchronously iterate over new messages and log them as they come in
await (let message of messages) {
nsole.log(message);


ole.log('Done!')

This module will automatically buffer incoming data if .next hasn't been called yet.

Options
cify(listenToNewMessages, {
 Close the database connection when the async iterator is done
 NOTE: This is passed whatever the listener resolves the returned promise with, in this case listenToNewMessages resolves with the database connection but it could be whatever you desire
Close: (connection) => { connection.close(); },
 Log errors to your error tracking system
Error: (err) => {
errorTracking.capture(err);

ffering: false

Credits

This module is heavily based on the event emitter to async iterator utility used in graphql-js. Also big shoutout to @ForbesLindesay who helped a ton with the initial implementation and understanding the problem.

License

Licensed under the MIT License, Copyright ©? 2017 Maximilian Stoiber. See LICENSE.md for more information.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.