Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created April 12, 2019 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/f2cb9575dee95d0189b7a1defb1f336d to your computer and use it in GitHub Desktop.
Save baweaver/f2cb9575dee95d0189b7a1defb1f336d to your computer and use it in GitHub Desktop.
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
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