Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created June 29, 2019 15:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkarpov15/51d533980925dcff107e923c4a7af607 to your computer and use it in GitHub Desktop.
Save vkarpov15/51d533980925dcff107e923c4a7af607 to your computer and use it in GitHub Desktop.
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