【问题标题】:Assignment shorthand with anonymous / arrow function callbacks带有匿名/箭头函数回调的赋值简写
【发布时间】:2018-03-07 22:33:36
【问题描述】:

我有这个代码示例:

 before('get all users', h => {
    return getAllUsers().then(function (users) {
      return h.supply.users = users;
    });
  });

我正在寻找一些速记,这是我能做到的最好的吗?

 before('get all users', h => {
    return getAllUsers().then(v => (h.supply.users = v));
 });

我在想也许我们可以使用一些替代的赋值技巧。

【问题讨论】:

  • before('get all users', h => getAllUsers().then(v => (h.supply.users = v)));
  • getAllUsers() 是否返回多个值?如果是这样,继续为h.supply.users 重新分配不同的值似乎很浪费,除非那是“setter”属性。

标签: javascript node.js arrow-functions


【解决方案1】:

你可以在一行中完成

   before('get all users', h => getAllUsers().then(v => h.supply.users=v));

【讨论】:

    【解决方案2】:

    我想你可以创建一个辅助函数,如下所示:

    const assign = function(v1){
        return function(v2){
           return v1 = v2;
        }
    };
    
    
    before('get all users', h => getAllUsers().then(assign(h.supply.users)));
    

    // 未经测试

    不是一个很好的解决方案,因为它可能会破坏一些 Object.defineProperty 钩子等。不建议这样做。 :)

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2019-10-21
      • 1970-01-01
      • 2020-07-30
      • 2012-10-23
      • 2018-07-02
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多