【问题标题】:Is it possible to spread the input array into arguments?是否可以将输入数组传播到参数中?
【发布时间】:2017-07-07 09:03:30
【问题描述】:

所以 Promise.all 将数组作为值传递给函数,我更愿意将数组值作为参数传递。

假设我有这个功能:

function printData(a,b,c){
   console.log(a,b,c)
}

我愿意

Promise.all([1,2,3]).then(printData)
>> [1,2,3] undefined undefined

改为打印这个

>> 1 2 3

有没有更好的方法:

Promise.all([1,2,3,4]).then(function(values){printData.apply(null, values)})

使用扩展运算符?

我也试过

Promise.all([1,2,3]).then(printData.apply)

但它返回一个错误

【问题讨论】:

    标签: javascript ecmascript-6 promise


    【解决方案1】:

    而不是

    .then(printData)
    

    你可以传播

    .then(args => printData(...args))
    

    【讨论】:

      【解决方案2】:

      使用 ES 6 的一种方法解构

      function printData(a,b,c){
         console.log(a,b,c)
      }
      
      Promise.all([1,2,3]).then( data => {var [a,b,c] = data;
                                 printData(a,b,c);});

      使用 ES 6 Spread 语法

      function printData(a,b,c){
         console.log(a,b,c)
      }
      
      Promise.all([1,2,3]).then(data => printData(...data))

      【讨论】:

        【解决方案3】:
        function printData(...a){
          console.log(a.reduce((n,o)=>n.concat(o),[]).join(","));
        }
        

        获取所有参数,将 Arrays 中的所有 Arrays 减少为一个 Array,将其作为参数传递给 console.log。

        http://jsbin.com/vutizahago/edit?console

        【讨论】:

        • @lonewarrior556 真的吗?你试过 Promise.all([1,2,3]).then(printData)
        【解决方案4】:

        从技术上讲,尝试使用扩展运算符会让您嵌套函数,这可行,但还有另一种方法

        Promise.all([1,2,3]).then(printData.apply)

        不起作用,因为这等于:

        printData.apply.call(undefined, [1,2,3])
        

        返回相同的错误

        >>Uncaught TypeError: Function.prototype.apply was called on undefined,
         which is a undefined and not a function
        

        Promisethis 传递给call,但它会忘记它应该是什么。 你想要的是:

        test.apply.call(test,[null,1,2,3])
        

        等于:

        test.apply(null,[1,2,3])
        

        等于

        test(1,2,3)
        

        因为您无法使用 call 控制 Promise,所以使用 bind 来确定参数

        printData.apply.bind(printData, null)
        

        调用时等于

        printData.apply.bind(printData, null).call(undefined, [1,2,3])
        >> 1 2 3
        

        最后:

        Promise.all([1,2,3]).then(printData.apply.bind(printData,null))
        >> 1 2 3
        

        这是一个关于结合 apply 和 call 的相关问题 Why can I not call a function.apply?

        【讨论】:

          猜你喜欢
          • 2016-12-08
          • 2011-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-07
          • 1970-01-01
          • 2021-11-11
          • 1970-01-01
          相关资源
          最近更新 更多