Success and Failure Callback Functions - I Don't Understand why (resolvedValue) works this way!

Hey all. I’m working on this: and in the examples theres a bit of code I don’t fully understand.

Heres the code:

const prom = new Promise((resolve, reject) => { resolve('Yay!'); }); const handleSuccess = (resolvedValue) => { console.log(resolvedValue); }; prom.then(handleSuccess); // Prints: 'Yay!'

In this example, what exactly is resolvedValue doing? is this a pre-set function in Javascript? Does javascript automatically know what “resolvedValue” means?

We dont ever set resolvedValue. I dont understand how its getting the value of the resolved output of the promise…

Hey @micro0544424663 !

This is a good question. Let’s start from the beginning. When your code calls on new Promise() it creates an object with some baked in functions. One of which is .then . This function handles resolved promises. It accepts functions called callback functions. These functions take the resolved value, which in this case is Yay! and then handles the resolved value.

In reallity resolvedValue is just a parameter in your callback function, and it will eventually be passed the resolved value as an argument.

Let me know what you think.


1 Like

Thanks, @mdwiltfong thats helpful. What I still dont understand is how resolvedValue gets passed the resolved value of the promise passed to it.

In that handleSuccess function resolvedValue is being declaired for the first time and used as a parameter. How does the system know that resolvedValue should hold the resolved outcome of the promies?

Let me ask it this way, does prom.then(someFunction) ALWAYS pass the succueeful out come of a promise? is .then always passing the successful outcome of a promise to the function in the statement?

what exactly is resolvedValue doing?

This is simply the value that’s passed to the function. You could literally call the function stand alone:

handleSuccess('hello world says resolvedValue');

Alternately, the promise then could have an anonymous function, which could be easier to follow:

    .then(resolvedValue => console.log("promise result", resolvedValue))

@micro0544424663 ,

That’s good to hear!

So I don’t know the specifics of how it does it, but i’m willing to bet that it uses a callback function. Here is an example of what I think .then() is doing behind the scenes:

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;

myCalculator(5, 5, myDisplayer);

In this example, myDisplayer is your handleSuccess function.