mirror of
https://github.com/micropython/micropython.git
synced 2025-09-07 18:30:27 +02:00
This commit adds a significant portion of the existing MicroPython asyncio module to the webassembly port, using parts of the existing asyncio code and some custom JavaScript parts. The key difference to the standard asyncio is that this version uses the JavaScript runtime to do the actual scheduling and waiting on events, eg Promise fulfillment, timeouts, fetching URLs. This implementation does not include asyncio.run(). Instead one just uses asyncio.create_task(..) to start tasks and then returns to the JavaScript. Then JavaScript will run the tasks. The implementation here tries to reuse as much existing asyncio code as possible, and gets all the semantics correct for things like cancellation and asyncio.wait_for. An alternative approach would reimplement Task, Event, etc using JavaScript Promise's. That approach is very difficult to get right when trying to implement cancellation (because it's not possible to cancel a JavaScript Promise). Signed-off-by: Damien George <damien@micropython.org>
45 lines
982 B
JavaScript
45 lines
982 B
JavaScript
// Test asyncio.create_task(), and tasks waiting on a Promise.
|
|
|
|
const mp = await (await import(process.argv[2])).loadMicroPython();
|
|
|
|
globalThis.p0 = new Promise((resolve, reject) => {
|
|
resolve(123);
|
|
});
|
|
|
|
globalThis.p1 = new Promise((resolve, reject) => {
|
|
setTimeout(() => {
|
|
console.log("setTimeout resolved");
|
|
resolve(456);
|
|
}, 200);
|
|
});
|
|
|
|
mp.runPython(`
|
|
import js
|
|
import asyncio
|
|
|
|
async def task(id, promise):
|
|
print("task start", id)
|
|
print("task await", id, await promise)
|
|
print("task await", id, await promise)
|
|
print("task end", id)
|
|
|
|
print("start")
|
|
t1 = asyncio.create_task(task(1, js.p0))
|
|
t2 = asyncio.create_task(task(2, js.p1))
|
|
print("t1", t1.done(), t2.done())
|
|
print("end")
|
|
`);
|
|
|
|
// Wait for p1 to fulfill so t2 can continue.
|
|
await globalThis.p1;
|
|
|
|
// Wait a little longer so t2 can complete.
|
|
await new Promise((resolve, reject) => {
|
|
setTimeout(resolve, 10);
|
|
});
|
|
|
|
mp.runPython(`
|
|
print("restart")
|
|
print("t1", t1.done(), t2.done())
|
|
`);
|