FAQ: JavaScript Promises - Constructing a Promise Object

This community-built FAQ covers the “Constructing a Promise Object” exercise from the lesson “JavaScript Promises”.

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

Asynchronous JavaScript
Asynchronous JavaScript

FAQs on the exercise Constructing a Promise Object

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!

1.

You’ll be writing your code in the code-editor, but we won’t be running it until the final step. To check your code for a step, you can press the “Check Work” button.

We’re going to create a promise representing ordering sunglasses from an online store. First, create the function, myExecutor() . Later on, you’ll pass this function into the Promise constructor.

myExecutor() should:

  • Have two parameters: resolve and reject
  • Check if the sunglasses property on the inventory object has a value greater than zero
  • If it does, myExecutor() should invoke resolve() with the string 'Sunglasses order processed.'
  • If it does not, myExecutor() should invoke reject() with the string 'That item is sold out.'

The answer to part one above is as follows , but before we dive into the code below , i wanted to highlight the key aspects, that we are using the ES6 syntax , arrow functions, the 'new ’ keyword
for objects and the use of 'const ’ to declare variables .Ok now , the fun part .

const myExecutor = (resolve, reject) => {
    if (inventory.sunglasses > 0) {
        resolve('Sunglasses order processed.');
    } else {
        reject('That item is sold out.');
    }
};

The explanation is very simple , we are creating a arrow function and then we are making use of if and else statements in to check for a certain condition in the object inventory and we do that by referencing the object and its properties inside like below , this is very important because we can not just reference the property directly of an object .JS doesn’t know that

if (inventory.sunglasses > 0) {
        resolve('Sunglasses order processed.');

2.

Create a function, orderSunglasses() . This function should have no parameters. It should return a new promise constructed by passing your myExecutor() function into the Promise constructor.

const orderSunglasses = () => {
    return new Promise(myExecutor);
};

```This is pretty self explanatory 

**3.**

Create a variable  `orderPromise`  assigned to the returned value of your  `orderSunglasses()` function.

const orderPromise = orderSunglasses();


This is even easier , hope this helps the students .
3 Likes

Why is the function orderSunglasses used, as opposed to simply creating a variable which is set equal to a new promise.

let order = new Promise(myExecutor);
console.log(order);
9 Likes

Why does Step 1 of the exercise fail the check if you use a function declaration instead of an arrow function? Both should accomplish the same thing, and I would expect functionality to be more important than using a specific syntax option.

5 Likes

For me it just failed any way. I even copied the solution. Still didn’t seem to be correct.

1 Like

What does this mean? :

Promise { ‘That item is sold out.’ }
(node:680) UnhandledPromiseRejectionWarning: Un
handled promise rejection (rejection id: 1): Th
at item is sold out.
(node:680) DeprecationWarning: Unhandled promis
e rejections are deprecated. In the future, pro
mise rejections that are not handled will termi
nate the Node.js process with a non-zero exit c
ode.

5 Likes

I had the same question. So I googled, and found this StackOverflow discussion.

It seems we need .catch() to handle a promise rejection. We will learn it in the 7th lesson in this module.

6 Likes

Step 2 says:

Create a function, orderSunglasses(). This function should have no parameters.
It should return a new promise constructed by passing your myExecutor()
function into the Promise constructor.

Ok, so then why is this wrong?

function orderSunglasses(){
return new Promise(myExecutor);
};

Why can I only proceed to the next step if I write it like this?

const orderSunglasses = () => {
return new Promise(myExecutor);
};

2 Likes

Hello all
Why object this can t be used to acess sunglasses property ?
const myExecutor= (resolve,reject)=>{
if(this.sunglasses>0){
resolve(‘Sunglasses order processed.’);
}
else{
reject(‘That item is sold out.’);
}
}

I know this is months later, but I just got to this lesson, and am wondering if you got an answer to this question?

1 Like

This section needs some fixing. Why are we forced to write an arrow function declaration to create the Promise instead of just assigning the Promise instantiation to a constant? The example in the lesson copy is literally showing how to do it by const myPromise = new Promise(executorFunction) but the code checker is explicitly wanting you to do it in a arrow function declaration instead. It’s misleading, confusing, and unnecessary to force a different syntax choice that is different to the example you’re supposed to be learning from.

EDIT: After looking more closely, I think I see why it’s expecting to see an arrow function but it’s equally dumb and unnecessary. You’re supposed to create a function that returns the Promise and then create another variable that actually holds the promise returned by function. That’s completely unnecessary and confusing, as well as a bad example to learn from. That’s like doing this:
const bar = 1;
const foo = () => { return bar; }
const baz = foo();
instead of just assigning baz = 1. You’re introducing unnecessary and confusing steps.

Isn’t it because this is used from within the the local scope of a method to access another property’s value defined within the same object?

Here, we’re in the local scope of a function which is defined in global scope. I’m not sure if this could be used here to access other properties of the global object. However, even if it can, sunglasses is a property of the inventory object, so we are still left needing to access that object. The inventory object is defined in global scope, so we can simply access its sunglasses property from within the function using inventory.sunglasses .  And so the question of whether this could be used in some other way to do the same thing becomes irrelevant.

Any comments @mtf?

Consider,

var a = 6
let b = 7
c = a * b
console.log(window.a, window.b, window.c)
// <- 6 undefined 42
console.log(this.a, this.b, this.c)
// <- 6 undefined 42

Notice that var or no declaration keyword both create variables with bindings to the window object? And, that let does not?

this in the example above is window in the global object context.

const pi = Math.PI
console.log(pi, window.pi, this.pi)
// 3.141592653589793 undefined undefined

const is also similar to let in that there are no bindings to window.

You have the right idea in terms of object context. It gets even messier when we have objects within objects, since each has their own this object. The operative term is context. Without an object, there is none.

Functions also have a this object but it only comes into play when the function is a constructor. We know that all functions can be constructors, with some provisos. This applies to both declared functions and function expressions, however it may not apply to arrow syntax.

const Foo = x => {
  this.x = x;
}
y = new Foo(42)
<- Uncaught TypeError: Foo is not a constructor

That tells us that arrow functions do not have a this object.

Toss these concepts around for a little.

1 Like

Hi, I’m currently working on this problem and I had the same issue. The last answer is correct and should pass.


My 25 cents, missing a dot shouldn’t be the reason for not passing the test, when the whole concept is right. Some times you have the right answer, and u start dancing around & butchering your correct code.

2 Likes

And I’m even months later than you, still wondering the same question.

2 Likes

Hello! I’ve some problem with final output of this code. When I enter ‘node app.js’ in terminal, Syntax Error appears. I’ve done all tasks correctly in codepen but something went wrong and I don’t know why. Could you check my code? I’ll be very grateful.

return = ... is not a valid return statement. We cannot assign to the keyword.

return new Promise(...)
1 Like

Yes! You were right, my mistake.
I just wonder why CodeCademy decided to move me to the next step and approve my solution.
Weird. Thanks a lot!

1 Like

I had a lot of issues with Constructing a Promise Object as testing with Node through these errors:

Promise { ‘That item is sold out.’ }
(node:12936) UnhandledPromiseRejectionWarning: That item is sold out.
(node:12936) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12936) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is how I fixed it so it no longer throws errors:

const inventory = {

sunglasses: 0,
pants: 1088,
bags: 1344,
};

// Write your code below:
const myExecutor = (resolve, reject) => {
if (inventory.sunglasses > 0) {
resolve(“Sunglasses order processed.”);
} else {
reject(“That item is sold out.”);
}
};
const orderSunglasses = new Promise(function (resolve, reject) {
if (inventory.sunglasses > 0) {
resolve(“Sunglasses order processed.”);
} else {
reject(“That item is sold out.”);
}
});

orderSunglasses.catch(function (error) {
console.error(error);
});

console.log(orderSunglasses);