是否可以将输入数组扩展为参数?

lon*_*556 5 javascript promise ecmascript-6

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

假设我有这个功能:

function printData(a,b,c){
   console.log(a,b,c)
}
Run Code Online (Sandbox Code Playgroud)

我想

Promise.all([1,2,3]).then(printData)
>> [1,2,3] undefined undefined
Run Code Online (Sandbox Code Playgroud)

改为打印这个

>> 1 2 3
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点:

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

使用扩展运算符?

我也试过

Promise.all([1,2,3]).then(printData.apply)
Run Code Online (Sandbox Code Playgroud)

但它返回一个错误

Abh*_*dha 6

使用 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);});
Run Code Online (Sandbox Code Playgroud)

使用 ES 6扩展语法

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

Promise.all([1,2,3]).then(data => printData(...data))
Run Code Online (Sandbox Code Playgroud)


lon*_*556 0

尝试从技术上使用展开运算符可以让您嵌套函数,这很有效,但还有另一种方法

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

不起作用,因为这等于:

printData.apply.call(undefined, [1,2,3])
Run Code Online (Sandbox Code Playgroud)

返回相同的错误

>>Uncaught TypeError: Function.prototype.apply was called on undefined,
 which is a undefined and not a function
Run Code Online (Sandbox Code Playgroud)

Promise传递thiscall并且它失去了它应该是什么的轨迹。你想要的是:

test.apply.call(test,[null,1,2,3])
Run Code Online (Sandbox Code Playgroud)

等于:

test.apply(null,[1,2,3])
Run Code Online (Sandbox Code Playgroud)

这等于

test(1,2,3)
Run Code Online (Sandbox Code Playgroud)

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

printData.apply.bind(printData, null)
Run Code Online (Sandbox Code Playgroud)

当调用时等于

printData.apply.bind(printData, null).call(undefined, [1,2,3])
>> 1 2 3
Run Code Online (Sandbox Code Playgroud)

所以最后:

Promise.all([1,2,3]).then(printData.apply.bind(printData,null))
>> 1 2 3
Run Code Online (Sandbox Code Playgroud)

这是关于组合 apply 和 call 的相关问题 为什么我不能调用 function.apply?