Created
June 29, 2019 15:57
-
-
Save vkarpov15/51d533980925dcff107e923c4a7af607 to your computer and use it in GitHub Desktop.
Example of reporting on progress using an async generator function and websockets
This file contains hidden or 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
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