問題描述
如何在 JavaScript 中實現動態回調參數 (How can I achieve dynamic callback arguments in JavaScript)
如何在 JavaScript 中實現動態回調參數
我要編寫三個函數。我為什麼這樣做是因為我想封裝 initDB 的細節,這樣我可以寫更少的代碼。下面是它的樣子:
const initDB = (schemas: any[]) =>
Realm.open({ path: 'CircleYY.realm', schema: schemas })
.then((realm: Realm) => ({ realm }))
.catch((error: Error) => ({ error }));
所以基本上這個函數只是初始化一個數據庫,它會返回一個數據庫實例或一個錯誤。
我還有一些特定的數據庫寫入函數,比如下面這個:
// Delete a message
const deleteOrder = (orderID: string, realm: Realm) => {
realm.write(() => {
const order = realm.objects('Orders').filtered(`primaryKey = ${id}`);
realm.delete(order);
});
};
我下面有這三個函數:
makeDBTransaction(deleteOrder(id));
and
makeDBTransaction(writeCommentInOrder(orderId, comment))
和
const makeDBTransaction = async (callback: Function) => {
const { error, realm } = (await initDB([
OrderSchema,
ProductSchema,
])) as InitRealm;
if (error) return { error };
callback(realm); // Pass realm while maintaining the arguments specified in the callback which is dynamic
return realm.close();
};
參考解法
方法 1:
I think you can keep adding arguments in an array in a required order and then apply the arguments to the function and call that function.
//for example
function foo1(x, y) {
console.log(x,y);
}
function foo2(cb, y) {
const x = 3;
cb.apply(null, [x,y]);
}
foo2(foo1, 5);
//So your code will be like this
makeDBTransaction(deleteOrder, [id]);
const makeDBTransaction = async (callback: Function, arg: any[]) => {
const { error, realm } = (await initDB([
OrderSchema,
ProductSchema,
])) as InitRealm;
if (error) return { error };
arg.push(realm);
callback.apply(null, arg);
return realm.close();
};