// Custom promisify function
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn(...args, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
}
#is promisify necessary? i am working with bun:sqlite .get etc which are all synchronous
1 messages · Page 1 of 1 (latest)
util.promisify?
yeah i found it, but its awkward to use because sqlite api is awkward
thanks
you can not use promisify on a class member function!
const myrun = promisify(Statement.run)
no go
i have to manually wrap any sections i think might need it
i dont like it but this is sqlite because the entire api is syncronous but we usually want async for web request db access (from what i have seen)
its fine, i am just frustrated that the sqlite api did not think to provide async for anything, im sure most of the time people will be wrapping that stuff up in promises
and this is the case with every sqlite api for js ive used
so i should of just sucked it up instead of moaning here, i feel like deleting all this, i've been going back and forth with balancing return on success throw on error vs error return types (sqlite api does this) so, which also plays into how you manage async, its all rather LOOSY GOOSY
🦆
you can
just bind it
or reassign the method on the object
i settled on the following pattern ( trying to stick with return on success throw on fail) ... i avoid bind usually
import { Database, Statement, Changes } from "bun:sqlite";
import { User, UserError } from "./user";
const mydb: Database = new Database("mydb.sqlite");
const insert_sql: string = "insert into Users (username,password_hash,password_salt,email) Values(?,?,?,?)";
const insert_stmt: Statement = mydb.query(insert_sql);
const select_by_user_id_sql: string = "select * from Users where user_id = ?";
const select_by_user_id_stmt: Statement = mydb.query(select_by_user_id_sql).as(User);
const log = (o: Object) => {
console.log('test log: ' + JSON.stringify(o));
}
const insert_user = async (username: string, hash: string, salt: string, email: string): Promise<User> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(UserError.DatabaseInsertTimeout);
}, 1000);
const i_result: Changes = insert_stmt.run(username, hash, salt, email);
if (!i_result?.lastInsertRowid) {
reject('insert_user: ' + JSON.stringify(i_result));
}
const s_result: unknown = select_by_user_id_stmt.get(i_result.lastInsertRowid);
if (s_result instanceof User) {
resolve(s_result as User);
}
reject('insert_user: ' + JSON.stringify(s_result));
});
}
const test = async () => {
const u: User = await insert_user("bob2", "black", "sea", "[email protected]");
const uu: User = await insert_user("bob3", "black", "sea", "[email protected]");
log(u); log(uu);
}
try {
await test()
} catch (e) {
console.log('test catch: ' + e);
}
any comments would be appreciated