Codecademy Forums

FAQ: JavaScript Promises - The onFulfilled and onRejected Functions

Hello guys,
I have a question related to part 6, specifically to this example:

04

If ‘handleSuccess’ and ‘handleFailure’ are functions that take in one argument, why when they are inserted in ‘then(handleSuccess, handleFailure)’ don’t take any arguments?

I’ve the doubt that’s a stupid question but I must resolve this.

Thanks for your answer.

1 Like

callbacks do not take arguments because they are not invoked when passed in. Only the representation of the function is given. The then method will invoke the one that matches the outcome. The first callback is for success, the second for failure. then decides which to use and gives the appropriate argument at that time.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

1 Like

Thank you, that’s clear now.

1 Like

Can someone help me to understand the indexing that is happening on this line?

let inStock = order.every(item => inventory[item[0]] >= item[1]);

I’m confused about what appears to me to be a mismatch in the index which just my not understanding what is really happening here.

thanks,

josh

The every iterator returns a boolean. It will be true if every item in an array meets the condition.

Above, element 0 is compared to element 1 and cannot be less than else the return will be false. We’re assuming that inventory is made up of smaller arrays with at least two elements each.

There is nothing amiss with the indices.

 > a = [[3,2],[3,3],[3,1]]
<- (3) [Array(2), Array(2), Array(2)]
 > a.every(x => x[0] >= x[1])
<- true
 > b = [[3,4],[3,3],[3,1]]
<- (3) [Array(2), Array(2), Array(2)]
 > b.every(x => x[0] >= x[1])
<- false
2 Likes

thanks that helped a lot!

1 Like

I don’t think I fully understand this code in the example:

const prom = new Promise((resolve, reject) => {
resolve(‘Yay!’);
});

const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};

prom.then(handleSuccess); // Prints: ‘Yay!’

Is an anonymous function being declared inside the Promise() function instead of declaring it separately and then passing it into Promise() like we did before?

Also, how does it know what to pass in for the “resolvedValue” parameter?

Ok, this is a really dumb question, but I seem to run into the same issue a lot, the way I am thinking about this, so if anyone could help, that would be great.

const {checkInventory} = require(’./library.js’);

const order = [[‘sunglasses’, 1], [‘bags’, 2]];

// Write your code below:
const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};

const handleFailure = (rejectReason) => {
console.log(rejectReason);
};

checkInventory(order)
.then(handleSuccess, handleFailure);

What I want to know is, why does the program know that the resolvedReason or rejectReason points to checkInventory(order)? How does the program know these are connected?