Skip to content

Instantly share code, notes, and snippets.

@arikw
Created September 12, 2021 07:47
Show Gist options
  • Save arikw/280330095d4adb6110464841863e064c to your computer and use it in GitHub Desktop.
Save arikw/280330095d4adb6110464841863e064c to your computer and use it in GitHub Desktop.
A proof-of-concept: How to create a promise that calls the rest of the code without wrapping it with an executor function

A proof-of-concept: How to create a promise that calls the rest of the code without wrapping it with an executor function

function promised(callerArgs) {
  const caller = callerArgs.callee;
  if (!caller.resolve) {
    return {
      promise: new Promise((resolve, reject) => {

        caller.resolve = resolve;
        caller.reject = reject;

        caller.apply(this, Array.prototype.slice.call(callerArgs));
      })
    };
  }
  return { resolve: caller.resolve, reject: caller.reject, inPromise: true }
}

function test() {
  const { resolve, reject, inPromise, promise } = promised(arguments);
  if (!inPromise) return promise;

  setTimeout(() => resolve('resolved!'), 1000);
}

function testWithRejection() {
  const { resolve, reject, inPromise, promise } = promised(arguments);
  if (!inPromise) return promise;

  setTimeout(() => reject(123), 1000);
}

function testWithException() {
  const { resolve, reject, inPromise, promise } = promised(arguments);
  if (!inPromise) return promise;

  throw 'omg';
}

console.log(await test().catch(err => console.error('got an error', err)));
await testWithRejection().catch(err => console.error('got an error', err));
await testWithException().catch(err => console.error('got an error', err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment