0

In this code block:

  1. if I declare resolve / reject with const keyword,

    I need to pass them into executor function without this, and using this will get error;

  2. if I declare resolve / reject with this keyword,

    I need to pass them into executor function with this.

What cause this different behavior?

And what differences between these two ways?

Please help me, thanks~

class myPromise {
  constructor(executor) {
   
    this.status = PENDING;
    this.value = null;
    this.reason = null;

    const resolve = value => {
      this.value = value;
    }

    this.reject = reason => {
      this.reason = reason;
    }
  
    // Why not use this.resolve / this.reject ?
    // 
    executor(resolve, this.reject);
  }

  then(onfulfilled = Function.prototype, onrejected = Function.prototype) {
    onfulfilled(this.value);

    onrejected(this.reason);
  }
}

1 Answer 1

2

Why not use this.resolve / this.reject ?

this.resolve wouldn't work because resolve is not part of this. Recall that variables declared with const are only accessible in block in which they are declared, which in this case, is constructor { ... } (docs).

On the other hand, when you say this.reject you are actually assigning that value to this, and have to use this. every time you want to refer to this value again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.