Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to spread the input array into arguments?

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

like image 870
lonewarrior556 Avatar asked Feb 17 '17 18:02

lonewarrior556


People also ask

Can we pass array as argument in C?

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.

Can we pass array as argument in JS?

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.

How do you pass an entire array to a function as an argument?

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.

Can you spread an array into an object?

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!


1 Answers

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))
like image 70
Abhinav Galodha Avatar answered Nov 14 '22 21:11

Abhinav Galodha