Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helpers for working with ActionCable async on the client side
// Helpers
const MAX_WAIT = 10000;
const POLLING_RATE = 500;
export function timedOut (maxWait) {
const startTime = Date.now();
return () => Date.now() - startTime > maxWait;
}
export function waitUntilTime (timestamp, action) {
const arrivalTime = timestamp - Date.now();
setTimeout(action, arrivalTime);
}
export function waitUntil (condition, maxWait = MAX_WAIT) {
return new Promise((resolve, reject) => {
const isTimedOut = timedOut(maxWait);
const waitInterval = setInterval(() => {
if (condition()) {
clearInterval(waitInterval);
return resolve();
}
if (isTimedOut()) {
clearInterval(waitInterval);
return reject('Request timed out!');
}
}, POLLING_RATE);
});
}
export function waitUntilConnected (channel) {
return waitUntil(channel.consumer.connection.isOpen;
}
// Demo Usecase:
import cable from 'actioncable';
const consumer = cable.createConsumer();
const channel = consumer.subscriptions.create({
channel: "MyChannel",
param: "something"
}, { /* ... */ });
waitUntilConnected(channel).then(() => {
// Do something that relies on the channel being live
})
@dhh

This comment has been minimized.

Copy link

dhh commented Apr 12, 2019

Am I misunderstanding the timing, or is this what the #connected callback provides in the js channel base class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.