DEV Community

loading...

Discussion on: Would it make sense to have "Symbol.promise" as standard JavaScript Symbol?

Collapse
ashsearle profile image
Ash

I don't know enough about the mechanics and overhead of await to comment on that.

In the Promise.race case, it seems to handle primitives and thenables directly, so there may not be any need to wrap as a 'real promise'.

Reading up on Promise.resolve - is there a reason you can't use Promise.resolve(thenable) rather than spreading args with your new Promise idiom?

I find the Promise part of the EcmaScript spec really hard to read, so refer to the comments against Promise.resolve on MDN:

If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value

Thread Thread
noseratio profile image
Andrew Nosenko Author

It never occurred to me I could use a thenable with Promise.resolve and Promise.race etc. Today I've learnt something new, thanks to you! It really does work:

export {}

class Thenable {
  #promise;

  constructor(ms) {
    this.#promise = new Promise(r => setTimeout(r, ms)); 
  }

  then(...a) { return this.#promise.then(...a); }
}

await Promise.resolve(new Thenable(2000));

await Promise.race([new Thenable(2000)]);
Enter fullscreen mode Exit fullscreen mode

I don't know enough about the mechanics and overhead of await to comment on that.

I could recommend this read on V8.dev: Faster async functions and promises.

Forem Open with the Forem app