So Promise.all passes an array as a value into the function, I would much rather it pass the array values as arguments.
Assume I have this function:
function printData(a,b,c){
console.log(a,b,c)
}
I would like
Promise.all([1,2,3]).then(printData)
>> [1,2,3] undefined undefined
To print this instead
>> 1 2 3
Is there a better way of doing this:
Promise.all([1,2,3,4]).then(function(values){printData.apply(null, values)})
using the spread operator?
I also tried
Promise.all([1,2,3]).then(printData.apply)
But it returns an error
Just like normal variables, Arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
Use the spread syntax (...) to convert an array to an object, e.g. const obj = {... arr} . The spread syntax will unpack the values of the array into a new object, where the indexes of the array are the object's keys and the elements in the array - the object's values. Copied!
One way using ES 6 Destructuring
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);});
Using ES 6 Spread Syntax
function printData(a,b,c){
console.log(a,b,c)
}
Promise.all([1,2,3]).then(data => printData(...data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With