Skip to main content
aayushprime.

Note

Custom Thenable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const thenable: PromiseLike<string> = {
  then<TResult1 = string, TResult2 = void>(
    resolve: (value: string) => TResult1 | PromiseLike<TResult1>,
    reject: (reason: any) => TResult2 | PromiseLike<TResult2>,
  ): PromiseLike<TResult1 | TResult2> {
    return Promise.resolve("hello").then(resolve, reject);
  },
};

console.log("isPromise", thenable instanceof Promise); // false
const result = await thenable;
console.log("result", result); // hello

Cloudflare RPC mention an interesting construct in the JS promises here. They are using custom promise objects (that can be awaited) to batch (over the network) multiple RPC calls sequentially without awaiting the result of the first.

Using a thenable construct. When awaited, the thenable object will run the then and can resolve the promise. But since promises allow chaining, we must propagate the generic types TResult1 and TResult2 and return a PromiseLike.