简体   繁体   中英

How can I achieve dynamic callback arguments in JavaScript

How can I achieve dynamic callback arguments in JavaScript

I have a three functions I want to compose. Why am I doing this is because I want to encapsulate the details of the initDB so I can write less code. Here's what it looks like below:

const initDB = (schemas: any[]) =>
  Realm.open({ path: 'CircleYY.realm', schema: schemas })
    .then((realm: Realm) => ({ realm }))
    .catch((error: Error) => ({ error }));

So basically this function just initialize a DB and it will return a DB instance or an Error.

I also have some specific database write functions like this below:

// Delete a message
const deleteOrder = (orderID: string, realm: Realm) => {
  realm.write(() => {
    const order = realm.objects('Orders').filtered(`primaryKey = ${id}`);
    realm.delete(order);
  });
};

and I have this three functions below:

makeDBTransaction(deleteOrder(id));

and

makeDBTransaction(writeCommentInOrder(orderId, comment))

and

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

I also want to pass the realm into the callback that can have more than 2 arguments.

How can I achieve that?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM