2

I´m running several method calls that need to show the end user a loading modal and hide it when the method resturns a result. I was looking for a way to run this pre-call code and post-call code for every method without repeating code.

swal({
  title: "Saving...",
  onBeforeOpen: () => swal.showLoading()
});
Meteor.call("method", {/*params*/}, (err, res) => {
 //Do something
 swal.hide();
});

I want to be able to run those 2 swal codes without writing that code in each call. Is there some way to configure Meteor.call to do something before and after the call to the method?

4

1 回答 1

1

您可以将代码抽象为一个包装函数,该函数接受您的方法名称、参数和回调函数作为参数:

const call = ({ title, name, params, callback }) => {
 swal({
  title: title,
  onBeforeOpen: () => swal.showLoading()
 });
 Meteor.call(name, params, (err, res) => {
   callback(err, res);
   swal.hide();
 });
}

请注意,这callback不是“真实”回调,而是放在语句中并从“真实”回调本身接收参数作为参数。

使用例如这样的方法:

call({ 
  title: 'Saving...', 
  name: 'method', 
  params: {/*params*/}, 
  callback: (err, res) => {
    console.log('I am executed before hide');
  }
});

如果你需要这个功能很多,你可以把它放在一个自己的文件中,并使用export它来使其可用于其他文件/模块。

于 2019-01-09T18:50:18.160 回答