FAQ: JavaScript Promises - Using Promise.all()

To call a function, we use functionName(parameters). That’s left empty if there are no parameters.
Now check what checkSunglasses, checkPants, and checkBags are. Are they functions? No. If this confusing to you, I suggest you review functions. checkSunglasses, checkPants, and checkBags store the result of calling checkAvailability(itemName, distributorName) on a certain item and distributor.

If you look at the code for checkAvailability(itemName, distributorName), you’ll see that it returns a promise. Then we call Promise.all(promises) on an array of promises! Since checkSunglasses, checkPants, and checkBags are the results of calling checkAvailabity(itemName, distributorName), they are promises, so we can make them items of that array.

Edit: Whoops, I didn’t see the indirect comment chains that already answered the question. Hope someone finds this useful anyways.

Regarding itemsArray array on app.js file:

  1. Where in the code I see it is declared as an array?
  2. How do it gets its variables from? Is it from the resolve(itemName) on checkAvailability function on library.js file ?

Thank you, I just love to understand it all.

Hi,

Could anyone help me with this exercise. I can’t seem to past step 3.
This is my code:

const promise checkSunglasses = checkAvailability(‘sunglasses’, ‘Favorite Supply Co.’);

const promise checkPants = checkAvailability(‘pants’, ‘Favorite Supply Co.’);

const promise checkBags = checkAvailability(‘bags’, ‘Favorite Supply Co.’);

Promise.all([checkSunglasses, checkPants, checkBags]).then(onFulfill).catch(onReject);

Code academy is popping up with a syntax error and when I execute the code, it produces also a syntax error directing to ‘sunglasses’. I have been staring at this for far too long and I feel like I must be missing something obvious here.

Many thanks in advance.

1 Like

So technically, this below shouldn’t work? We were using an arrow function in .then and .catch all long, and now it is not working?

Promise.all([checkSunglasses, checkPants, checkBags])
.then((onFulfill) => {console.log(onFulfill)})
.catch((onReject) => {console.log(onReject)})

@midlindner

Promise.all([checkSunglasses, checkPants, checkBags]).then(onFulfill));

it should work. :crossed_fingers:

I copied and pasted what you said and it still gives me a red ‘X’ on step 4?

Would need to see your code, and the error message if one was provided in order to hazard a guess as to why.

I see what I did! I put a ; after the .then statement. Evidently you cannot continue to the .catch statement if you do that!

Thank you for the quick reply!

  1. As I understand (and that’s not a very hopeful premise), it’s because the resolution of the promises from the functions checking availability is the item name if they are all successful. Meaning that if Promise.all resolves, the argument is passes is the array of all the resolutions.

  2. Yes as I alluded to in answer (1), we have this bit of code in ‘library.js’

if (restockSuccess()) {
     console.log(`${itemName} are in stock at ${distributorName}`)
     resolve(itemName);
}

For each of the variable which calls ‘checkAvailability’ function returns promise (as given in library.js module), either resolved with ‘ItemName’ or rejected with reason.

Case 1: When all promises resolved, it would return ‘ItemName’ for each ‘checkAvailability’ function

const checkSunglasses = checkAvailability('sunglasses', 'Favorite Supply Co.');
const checkPants = checkAvailability('pants', 'Favorite Supply Co.'); 
const  checkBags = checkAvailability('bags', 'Favorite Supply Co.');

Now, the values returned from these are stored in Array inside Promise.all()

let myPromise = Promise.all([checkSunglasses, checkPants, checkBags]);

so for all promises resolved, we would get the output like below

let myPromise = Promise.all(['sunglasses', 'pants', 'bags']);

which when used with .then() and .catch(), would give the expected result.

Case 2: When any of the promises fail, this would trigger catch() and would call onReject

Hope this makes sense !!

My version of the code is below:

  • I used the similar way they have explained in example to call ‘.then()’ and ‘.catch()’. Initially I have to make it work the way the program wanted to make pass step 4 to 6. Later, I changed as below, it gives me the same result. This way, I could understand in better way what variable is passed and into which function.

Please let me know, if there is any other ways of writing this… :slight_smile:
Thanks

My question is actually a small maybe unrelated question regarding the random 80% true/false generator at the end… don’t exactly nderstand the syntax of the ‘Math.random() > .2’ how does the > signb work in this case?
Thanks in advance :slight_smile:

I am getting the following output on the console:
bags are in stock at Favorite Supply Co.
pants are in stock at Favorite Supply Co.
Error: sunglasses is unavailable from Favorite Supply Co. at this time.

So I think the promise.all works in this fashion that it executes the success handler for each promise of the array first, and in case a promise was rejected it executes the failure handler at last? The code is as follows:

Promise.all([checkSunglasses, checkPants, checkBags])
.then(onFulfill)
.catch(onReject);

1 Like

You must not forget that functions are objects, so you pass them around. Since you already declared the functions over here:

const checkSunglasses = checkAvailability('sunglasses', 'Favorite Supply Co.');
const checkPants = checkAvailability('pants', 'Favorite Supply Co.');
const checkBags = checkAvailability('bags', 'Favorite Supply Co.');

You only need to reference them here (not calling them inside the function):

Promise.all([checkSunglasses, checkPants, checkBags])

Please correct me if I’m wrong :slight_smile:

  • Math.random generates a random number between 0 and 1 (not including 1)
  • The result of Math.random is then compared to 0.2
  • Assuming the results of Math.random are equally distributed on the scale between 0 and 1, they will be larger than 0.2 80% of the time.
  • So the comparison will return true 80% of the time, false 20% of the time.
1 Like

I’m still struggling about the onFulfill and onReject function.

I still don’t understand how theses two function are linked with the promise built with checkAvailability function, if someone can explain it to me ?

we have this function which return a promise

const checkAvailability = (itemName, distributorName) => {
    console.log(`Checking availability of ${itemName} at ${distributorName}...`);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (restockSuccess()) {
                console.log(`${itemName} are in stock at ${distributorName}`)
                resolve(itemName);
            } else {
                reject(`Error: ${itemName} is unavailable from ${distributorName} at this time.`);
            }
        }, 1000);
    });
};

and then

const onReject = (rejectionReason) => {
	console.log(rejectionReason);
};

// Write your code below:


let checkSunglasses = checkAvailability('sunglasses', 'Favorite Supply Co.');

let checkPants = checkAvailability('pants', 'Favorite Supply Co.');

let checkBags = checkAvailability('bags', 'Favorite Supply Co.');

Promise.all([checkSunglasses, checkPants,checkBags])
.then(onFulfill)
.catch(onReject)

How onFulfill will called the console.log “true” of checkAvailability ?

thanks ,

Still no expert answered convincingly why inside the Promise.all() function, you only reference and not call the three functions. Specially when the lesson’s code example is calling them (unlike the hint, which does reference them).

You’re calling the variables which store the returned value of having called them before:

const checkSunglasses = 
checkAvailability(`sunglasses`, `Favorite Supply Co.`);

const checkPants = 
checkAvailability(`pants`, `Favorite Supply Co.`);

const checkBags = checkAvailability(`bags`, `Favorite Supply Co.`);

//You're not storing a function here, but the returned value of the function. 
//Which is a promise. This could be either pending, or settled: resolved or rejected.

//later you pass an array of these promisses and their settled values as an argument to Promisse.all().

which ends up being the same: the promise or settled value of the promise from calling checkAvailability with the provided arguments.

…I think, or something like that.