Can you define a resolve function for Promises?

javascript

Solution

That understanding is not quite correct. The `resolve` function you define is not being used. When you call `resolve(5)`, you're instead using the `resolve` function that's being provided as an argument by the Promise constructor. The name `resolve` has no special meaning, you can use any name you want for this argument. For example, instead of `resolve` and `reject` we could call them `setValue` and `setError`:

var p = new Promise((setValue, setError) => {
  setTimeout(() => setValue(5), 1000);
});

You can see here why the function you defined called `resolve` was not being used when it was shadowed by the local definition of `resolve`.

The `resolve()` function you're given by the Promise constructor is only called by you, to provide a value to the Promise.

If you want to modify the value resulting resulting from a Promise, you need apply your filtering function using `.then(...)` (which gives you a new Promise with the modified value):

function doubleResult(x) {
  return x * 2;
}

var doubleP = p.then(doubleResult);
doubleP.then((doubledNumber) => {
  console.log(doubledNumber);
});

Problem

I'm getting up to speed with Promises, but there's one thing I don't understand. So, we define a Promise like so: ``` new Promise( /* executor */ function(resolve, reject) { ... } ); ``` I was under the impression that `resolve` is a function that I should call when the situation is resolved successfully. So I tried to do something like this: ``` function resolve(number) { return number * 2; } var p = new Promise((resolve, reject) => { setTimeout(() => resolve(5), 1000); }); p.then((doubledNumber) => { console.log(doubledNumber); // expected: 10, actual: 5 }); ``` So it seems like `resolve` isn't a function in the usual sense, it's more like a keyword like `return`. In other words, when I'm calling `resolve`, I'm just instructing the program to pass on whatever value is that I provide as the arg to `resolve`. Is my understanding correct?

Original source