Created
April 12, 2019 17:50
-
-
Save baweaver/f2cb9575dee95d0189b7a1defb1f336d to your computer and use it in GitHub Desktop.
Helpers for working with ActionCable async on the client side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Am I misunderstanding the timing, or is this what the #connected callback provides in the js channel base class?