Skip to content

Instantly share code, notes, and snippets.

@izelnakri
Last active October 10, 2024 02:13
Show Gist options
  • Save izelnakri/da59c815449614c937a5c057b5f38f0a to your computer and use it in GitHub Desktop.
Save izelnakri/da59c815449614c937a5c057b5f38f0a to your computer and use it in GitHub Desktop.
JS version of lua pcall, xpcall and attemp
let pcall = (func: Promise<Any> | Function, ...args) => {
if (func instanceof Promise) {
return new Promise(async (resolve) => {
let error
try {
return resolve([true, await promise])
} catch (err) {
error = err
}
return resolve([false, error])
})
}
try {
const result = func(...args);
return [true, result]; // Success, return result
} catch (error) {
return [false, error]; // Error occurred, return the error
}
}
let attempt = (func: Promise<Any> | Function, ...args) => {
if (func instanceof Promise) {
return new Promise(async (resolve) => {
let error
try {
return resolve([await promise, undefined])
} catch (err) {
error = err
}
return resolve([undefined, error])
})
}
try {
const result = func(...args);
return [result, undefined ]; // Success, return result
} catch (error) {
return [undefined, error]; // Error occurred, return the error
}
}
// xpcall has this behavior, 2nd argument func only gets call with(error obj) on error:
// function f(a, b)
// return a + b
// end
// status, ret = xpcall(f, debug.traceback, 1, 5)
// print(status)
// print(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment