Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing multiple arguments to promise resolution within setTimeout

I was trying to follow along with the MDN promise.all example but it seems I cannot pass more arguments to the setTimeout callback.

var p1 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 200, 1,2,3); 
});
var p2 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 500, "two"); 
});

Promise.all([p1, p2]).then(value => { 
  console.log(value);
}, reason => {
  console.log(reason)
});

This prints [1, "two"], where I would expect [1, 2, 3, "two"]. Doing this with setTimeout without promise fulfillment works as expected

setTimeout(cb, 100, 1, 2, 3);
function cb(a, b, c){
  console.log(a, b, c);
}
//=>1 2 3

Why doesn't this work with the promise? How can it be made to work with the promise?

like image 573
1252748 Avatar asked Sep 27 '16 17:09

1252748


1 Answers

The resolve function only takes a single argument. You can't change that as this is the spec.

Passing more than that doesn't make a difference, and your other values are ignored.

You can opt to pass an array to the resolve function, but you'll get an array on the then handler, not independent values like you wanted.

like image 189
Amit Avatar answered Oct 06 '22 03:10

Amit