ivandotv / pumpit

PumpIt is a small (<2KB) dependency injection container without the decorators, suitable for the browser.
MIT License
25 stars 2 forks source link

Async factory #95

Closed Jess182 closed 3 days ago

Jess182 commented 1 week ago

Is it possible to set async factory to return fulfilled promise? because when i log provider it still as a promise

container.bindFactory('DenoKV', () => {
    return Deno.openKv(Deno.env.get('DENO_KV_URL'));
}, { scope: SCOPE.SINGLETON });

image

ivandotv commented 1 week ago

I thought about creating async resolvers but eventually decided against it, because it would add a lot of complexity to the code base, and the file size would increase (I want to keep the file size low, so the package can be used for front end)

What you can do it resolve the value , and then await it

const myPromise = container.resolve('DenoKV')
await myPromise
// use promise result here
Jess182 commented 5 days ago

What you can do it resolve the value , and then await it

Yes, I did a workaround since the provider receives it through the constructor

constructor(private client: Deno.Kv) {
        if ('then' in client) {
            (client as any).then((result: Deno.Kv) => this.client = result);
        }
    }

However there are times when due to asynchronicity when some method uses the provider, it has not yet been "resolved"

But I appreciate the response and the clarification, cheers

ivandotv commented 3 days ago

FYI, you should not use async in your constructors.

this.client can still be a promise when you try to access it.

const yourClass = new Class()
yourClass.client // this is a promise
Jess182 commented 3 days ago

That's correct, that's why my initial question was if there was a way for the ioc container to have async factories