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));