Created
May 13, 2021 22:13
-
-
Save jamiebuilds/f06c8146d3e0bd58478ac9f5f86ce7b8 to your computer and use it in GitHub Desktop.
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
// Syntax proposal: | |
spawn { | |
await somethingAsync() | |
} | |
// `spawn` would be available wherever `await` is available | |
async function fn() { | |
await somethingAsync() | |
spawn { /* ... */ } | |
} | |
// `spawn` enables your code to run concurrently | |
console.log("logs 1st") | |
spawn { | |
await somethingAsync() | |
console.log("logs 3rd") | |
} | |
console.log("logs 2nd") | |
// `spawn` creates its own promise that can be `await`-ed at any time | |
let promise = spawn { /* ... */ } | |
// But that promise is also implicitly "await"-ed | |
let items = [] | |
async function fn() { | |
spawn { await sleepMs(200); items.push(1) } | |
spawn { await sleepMs(300); items.push(2) } | |
spawn { await sleepMs(100); items.push(3) } | |
} | |
await fn() | |
console.log(items) // [3, 1, 2] | |
// If any spawn's throw an error, it will be immediately thrown in the parent async context | |
let items = [] | |
async function fn() { | |
spawn { await sleepMs(200); items.push(1); throw new Error("wow") } | |
spawn { await sleepMs(300); items.push(2) } | |
spawn { await sleepMs(100); items.push(3) } | |
} | |
try { | |
await fn() | |
} catch (error) { | |
console.log(error, items) // "Error: wow", [3, 1] | |
} | |
// This would be very useful with `for await` loops to run them concurrently: | |
for await (const conn of Deno.listen({ port: 4500 })) { | |
spawn { | |
for await (const { respondWith } of Deno.serveHttp(conn)) { | |
respondWith(new Response(body)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment