0

I frequently create promises to block some calls to class instances until some asynchronous initialization completes (see example code).

I've also noticed running a benchmark that a promise's .then() call is fairly expensive, even though it's already resolved. A test function that ran ~50,000,000 calls per second was reduced to ~320,000 calls per second when wrapped in a resolved .then().

Is there a better practice of blocking calls much like with Promises?

Simple Example:

class SomeClass {
    constructor() {
        this.init_promise = new Promise(resolve => {
            return fetch("some json")
                .then(res => {
                    //  Do things with data.

                    return resolve();
                });
        });
    }

    getSomething() {
        return this.init_promise
            .then(() => {
                //  Return something
            });
    }
}
Nyaarium
  • 1,540
  • 5
  • 18
  • 34
  • 1
    Are you going to be calling it millions of times per second? If so, you can avoid the overhead by doing things synchronously when possible (set a boolean property when it resolves). If not, `async getSomething() { await this._init_promise; … }` might be more readable. – Ry- Aug 16 '18 at 22:54
  • firstly, benchmarks can be written badly :p secondly ... do you need to call that .then 50 million times a second? or even 320 thousand times a second? the .then has introduced a couple of milliseconds delay - is that going to impact your site? – Jaromanda X Aug 16 '18 at 22:55
  • 1
    Don't use the [`explicit promise construction anti-pattern`](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – charlietfl Aug 16 '18 at 23:09
  • Thanks all! I expect it to run maybe a few thousand time in a second at most. With our application as slow as it is, I'm just looking for easy optimizations before any large rewrites. – Nyaarium Aug 16 '18 at 23:16

0 Answers0