Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Created May 13, 2021 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiebuilds/f06c8146d3e0bd58478ac9f5f86ce7b8 to your computer and use it in GitHub Desktop.
Save jamiebuilds/f06c8146d3e0bd58478ac9f5f86ce7b8 to your computer and use it in GitHub Desktop.
// 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