Angular - 如何使用带参数的箭头函数?

时间:2017-08-15 08:18:33

标签: angular typescript

我有一个角度4的应用程序,我正在尝试编写一个行动队列。在上一个函数完成后将触发每个动作并获取其参数。



public activeRegistrationAndSync() {
    let actionsToPerformByOrder = [
       () => this.registrationComponent.activeFormValidators.apply(null, arguments),
       () => this.registrationComponent.register.apply(null, arguments),
       () => this.autoLogin.apply(null, arguments),
       () => this.postLogin.apply(null, arguments),
       () => this.checkout.apply(null, arguments)
    ];

    let defer = new Deferred<void>();
    let curPromise = defer.promise;

    //Build chain of acitons
    actionsToPerformByOrder.forEach(action => {
      curPromise = curPromise
        .then(action)
        .catch(err => this.error.emit(err));
    })

    //Active actions
    defer.resolve();
 }
 
 
 export class Deferred<T> {
  promise: Promise<T>;
  resolve: (value?: T | PromiseLike<T>) => void;
  reject:  (reason?: any) => void;

  constructor() {
    this.promise = new Promise<T>((resolve, reject) => {
      this.resolve = resolve;
      this.reject  = reject;
    });
  }
}
&#13;
&#13;
&#13;

我的问题是箭头函数不支持参数,而是使用function(){}而不是更改此引用。

2 个答案:

答案 0 :(得分:1)

我建议您使用async/await来合并并运行您的操作。它很容易阅读,这是基本的想法,用你的具体情况修改它:

async function activeRegistrationASync() {
  const actionsToPerformByOrder = [
    async (r) => {
      return Promise.resolve(3)
    },
    async (r) => {
      return Promise.resolve(r + 5)
    }
  ];

  let result;
  for (let action of actionsToPerformByOrder) {
    result = await action(result);
  }
  return result;
}

activeRegistrationASync().then((r) => {
  console.log(r);
});

答案 1 :(得分:0)

  1. 您可以使用

    之类的传播操作符

    (... rest)=&gt;的console.log(休息)

  2. 您可以使用bind功能

    function func(/ arguments /){console.log(this。arguments)}

    让a = func.bind(this)