Last active
March 7, 2025 14:42
-
-
Save Shoghy/ebc0c7a316054b26e9f2654fb4829b15 to your computer and use it in GitHub Desktop.
A kind of defer function in TS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function SelfPromiseFunc<Params extends Array<unknown>, ReturnType>( | |
func: (this: Promise<ReturnType>, ...params: Params) => ReturnType, | |
) { | |
return (...p: Params) => { | |
let resolve: (v: ReturnType) => void; | |
let reject: (v: unknown) => void; | |
const promise = new Promise<ReturnType>((rsv, rjc) => { | |
resolve = rsv; | |
reject = rjc; | |
}); | |
try { | |
const value = func.call(promise, ...p); | |
resolve!(value); | |
return value; | |
} catch (e) { | |
reject!(e); | |
throw e; | |
} | |
}; | |
} | |
export async function Defer(promise: Promise<unknown>, func: () => unknown) { | |
try { | |
await promise; | |
} catch (_) {} | |
func(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Waiter = SelfPromiseFunc(async function (value: string) { | |
Defer(this, () => { | |
console.log(value); | |
}); | |
await new Promise((resolve) => setTimeout(resolve, 1000)); | |
console.log("Hello"); | |
await new Promise((resolve) => setTimeout(resolve, 1000)); | |
console.log("SPACE"); | |
await new Promise((resolve) => setTimeout(resolve, 1000)); | |
}); | |
Waiter("World"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment