FAQ: JavaScript Promises - Chaining Multiple Promises

This community-built FAQ covers the “Chaining Multiple Promises” exercise from the lesson “JavaScript Promises”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Asynchronous JavaScript

FAQs on the exercise Chaining Multiple Promises

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

" In order for our chain to work properly, we had to return the promise secondPromiseFunction(firstResolveVal) . This ensured that the return value of the first .then() was our second promise rather than the default return of a new promise with the same settled value as the initial."

Still, I can’t understand why do we have to return the second promise. What could go wrong if we don’t? In the exercise I wrote:
checkInventory(order)
.then(processPayment)
.then(shipOrder)
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.log(errorMessage);
});

instead of the correct answer:
checkInventory(order)
.then((resolvedValueArray) => {
return processPayment(resolvedValueArray);
})
.then((resolvedValueArray) => {
return shipOrder(resolvedValueArray);
})
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.log(errorMessage);
});

They worked the same.

8 Likes

Hi @ran16 I had a look at the competition and they do it like you suggest.

It looks much simpler. I would love to hear if the Codecademy-preferred expression adds any value, and what value.

1 Like

I would like to know why

  1. let total = 0;
    itemsArr.forEach(item => {
    total += item[1] * store[item[0]].cost
    });

why do we need to set total = 0

why not just sum the total.

  1. why

generateRandomDelay())

what’s the point of delay, esp random delay here?

Thanks!

1 Like
  1. Because it is easy to set the total to 0(let total = 0;), and then work out of the price of items that has been ordered( item[1] * store[item[0]].cost), and add it to the total(total = total + item[1] * store[item[0]].cost). Because there are more than one items ordered, we need forEach() method to loop through the itemsArr several times, updating the total in every loop.
    Do you have a better way?

  2. They generated a random delay to simulate the reality where asynchronous operations often take some time.

1 Like

Maybe like reduce method? for sum

I think the reduce method only works for an array of numbers.
itemsArr is not an array of numbers.
You will need to loop through the itemsArr, get the items that have been ordered, find the single price, multiply by the quantity, push the total price of each different item into an array, and then use reduce()to sum it up. It is much more code to write.

I see, array or not array, thanks!!

1 Like

Sorry, I have to apologize. I was wrong to say that reduce method only works for an array of numbers. You can use reduce method to flatten a more complicated array. I just don’t know in this case how to do it yet. I have to let you know that I was wrong first.

2 Likes

Thank you for the update tho!

1 Like

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

array.every() method return either truth or false value, right?

I don’t understand this comparison. How does it work that if any item in stock have value 0, it returns false value?

What am I missing?

hey @mtf I am invoking you because it seems like in these last couple lessons there is nobody here to really answer the questions in the forum that some of the people have been asking, and you have helped me a couple times, which I greatly appreciate. With that said, I have a question regarding this lesson. I asked pretty much the same question in the forum thread regarding the previous lesson because they are more or less using the same code. that can be seen here

my question is regarding this line of code right here:

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

particularly this part

store[item[0]].inventory

isn’t store[item[0]] already equal to inventory? The way the code is written does not seem to be consistent with what we have learned in previous lessons regarding navigating through objects and arrays. But what’s even more baffling is that the last part of that line of code item[1] is actually consistent with what we’ve learned. When you look at the store object and the customer order object(which I will show below) each part of that equation store[item[0]].inventory >= item[1] is suppose to be referring to the number value of the object properties and array. store[item[0]].inventory is suppose to be referring to the inventory number(in the case of the sunglasses 817) and item[1] is suppose to be referring to the numbers in either of of those nested arrays [['sunglasses', 1], ['bags', 2]]. So what is this [0] doing in store[item[0]].inventory? isn’t store[item[0]] already equal to inventory?

Here is the store object:

const store = {
  sunglasses: {
    inventory: 817, 
    cost: 9.99
  },
  pants: {
    inventory: 236, 
    cost: 7.99
  },
  bags: {
    inventory: 17, 
    cost: 12.99
  }
};

Here is the order object with the items array:

const order = {
  items: [['sunglasses', 1], ['bags', 2]],
  giftcardBalance: 79.82
};

Here is the function with the line of code I am referring to:

const checkInventory = (order) => {
  return new Promise ((resolve, reject) => {
   setTimeout(()=> {  
   const itemsArr = order.items;  
   let inStock = itemsArr.every(item => store[item[0]].inventory >= item[1]);
   
   if (inStock){
     let total = 0;   
     itemsArr.forEach(item => {
       total += item[1] * store[item[0]].cost
     });
     console.log(`All of the items are in stock. The total cost of the order is ${total}.`);
     resolve([order, total]);
   } else {
     reject(`The order could not be completed because some items are sold out.`);
   }     
}, generateRandomDelay());
 });
};

Sorry for such a long post I believe it reads faster than it looks and thank you in advance!

1 Like

No, it is a store item (key, actually).

store['sunglasses']

We need to use the subscript since item is a variable.

2 Likes

Thank you for your response. I truly appreciate it but I am still a little confused. I understand that that store[item] is equivalent to saying store['sunglasses'] but the code says store[item[0]].inventory which makes me confused about the[0]. if this store[item] is equivalent to this store['sunglasses'] shouldn’t this store[item[0]] be equivalent to this store['sunglasses'].inventory? It seems that this store[item[0]].inventory appears redundant and looks as though that it would translate to this store['sunglasses'].inventory.inventory. What am I missing here? I get everything else about this lesson overall but this particular bit is racking my brain.

1 Like

Not quite, since item is also an array.

store[item[0]]  =>  store['sunglasses']

inventory is property of all the store objects.

store[item[0]].inventory  =>  817

So in a way the store part of store[item[0]] is redundant becauseitem is representing the store object. so shouldn’t [item[0]] => store['sunglasses'] why would store even be mention if item is already representing the store object. I just wish there was something to look at that explains this because a scenario like this was never explained when we learned about navigating arrays/objects. they never showed us a situation where a square bracket was nested in another like [item[0]] until this lesson. Maybe there is a way I can read up on that particular thing but I have no clue how to describe it. its not the same asitem[0]

item only represents a store object member, not store itself. Hence we need the parent object name in our references to its members.

1 Like

I appreciate your help on this. Is there anything that I can read or look into to better understand this?

2 Likes

suppose we dont care for using the value of first promise …
.

I don’t know how specific it is for JS, but when I had my intro to C class in university, initializing variables was definitely drilled into us.

At least in that case since the value of ‘total’ is always altered in reference to itself, you have to set it to some absolute value at some point.

As far as the random delay, it’s just a simulation of processes that can take time (think pulling a request from a network)