Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of reporting on progress using an async generator function and websockets
const WebSocket = require('ws');
// Core solver logic, stubbed out for example
async function* slow() {
yield 'starting...';
await new Promise(resolve => setTimeout(resolve, 10 * 1000));
// Use `yield` to report on progress
yield 'loading data...';
await new Promise(resolve => setTimeout(resolve, 10 * 1000));
yield 'running solver engine...';
await new Promise(resolve => setTimeout(resolve, 10 * 1000));
return { answer: 42 };
}
// WebSocket server
const server = new WebSocket.Server({
port: 8080
});
server.on('connection', function(socket) {
socket.on('message', async function(msg) {
if (msg !== 'solve') { return; }
const generator = slow();
let done = false;
while (!done) {
const next = await generator.next();
done = next.done;
socket.send(JSON.stringify(next));
}
});
});
// WebSocket client
const client = new WebSocket('ws://localhost:8080');
client.once('open', function() {
client.on('message', msg => {
msg = JSON.parse(msg);
console.log(new Date(), msg.value);
if (msg.done) {
client.close();
}
});
client.send('solve');
});
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.