1

I was reading some code using the Promise object.

There is a setTimeout function with three parameters, I am wondering what does the third parameter do? Because usually it only has two parameters.

The code is like below:

function timeout(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, ms , 'done');
    });
}
timeout(1000).then(value => {
    console.log(value);
});

I noticed that the third parameter is passed to the resolve function, but why can I use it in the function in then? How does it work?

Xan
  • 74,770
  • 16
  • 179
  • 206
Russell
  • 125
  • 2
  • 8
  • 4
    `'done'` will be supplied to `resolve` function when it will be invoked. `Additional parameters which are passed through to the function specified by function or code once the timer expires.` Read [docs](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) – Satpal Dec 10 '18 at 06:39
  • Related: [How can I pass a parameter to a setTimeout() callback?](/q/1190642/4642212), [Calling functions with setTimeout()](/q/3800512/4642212). – Sebastian Simon Sep 30 '21 at 03:47

2 Answers2

6

Below both examples can explain about it

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // expected output: Array [3, 42, "foo"]
});

The above example can be written as : -

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('foo');
  }, 100)
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // expected output: Array [3, 42, "foo"]
});

In short, third argument is the argument user needs to pass the the reference function [1st argument] given to setTimeout which is promise. We can call "arguments carry forward" to this feature.

Sahil Shikalgar
  • 761
  • 8
  • 20
-1

It's for passing additional parameters (arguments) that you might use in your function. These are not obligated.

Here's a link with more information about parameters and arguments: https://www.w3schools.com/js/js_function_parameters.asp

Hope this helps.

C4mps
  • 188
  • 10
  • 1
    so the third parameter is pass to the resolve function? – Russell Dec 10 '18 at 06:50
  • Not really... You just have the option to pass additional parameters with your function in case u might need them for some reason. I hardly use them... – C4mps Dec 10 '18 at 06:57