kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

Synchronous operation #163

Closed futpib closed 5 years ago

futpib commented 5 years ago

I'm submitting a ...

Sometimes a third party api forces you to run synchronously (this was the reason I could not integrate universal-router into my project). Or you want to just keep it simple or avoid extra unnecessary ticks.

Since consumers may already expect that resolve always returns a promise, this may be implemented by adding a resolveSync method.

frenzzy commented 5 years ago

@futpib hi, could you please show an example when/how it could be useful?

Or you want to just keep it simple or avoid extra unnecessary ticks.

Btw, do you know that promises are executed in the current event loop (tick) on a microtask queue?

futpib commented 5 years ago

could you please show an example when/how it could be useful?

I find myself writing an application inside a proprietary app container that expects that frontend code (which started as a simple template, which ran synchronously) to return html string synchronously. The code now contains a bunch of ifs testing the request path and begs for a router.

Btw, do you know that promises are executed in the current event loop (tick) on a microtask queue?

It's a queue anyway, right? Let's call ticks on the microtask queue microticks if this lessens confusion. Do you think microtask queue does not inflict overhead compared to synchronous code?

frenzzy commented 5 years ago

Ok, I think we're pretty much on the same page.

I don't want to add resolveSync method into the core because it will increase library size with not profit for most of the cases since loading a page usually is asynchronous process. I also believe that any web app could be designed with this in mind and maybe it is better to change design of your app earlier than later.

But I agree that synchronous router could be useful in some certain cases. What do you think about an add-on approach like we already have with url generation? For example something like:

import UniversalRouter from 'universal-router'
import resolveSync from 'universal-router/resolveSync'

const router = new UniversalRouter(routes)

resolveSync(router, pathnameOrContext) // => result

or

import UniversalRouter from 'universal-router'
import withResolveSync from 'universal-router/withResolveSync'

const Router = withResolveSync(UniversalRouter)
const router = new Router(routes)

router.resolveSync(pathnameOrContext) // => result

or

import UniversalRouter from 'universal-router/sync'

const router = new UniversalRouter(routes)

router.resolve(pathnameOrContext) // => result