Understanding the JavaScript Promise from Promise's "Source Code"/Thanks GitHub Copilot!
A Promise -- I wish I had a better image...

Understanding the JavaScript Promise from Promise's "Source Code"/Thanks GitHub Copilot!

Understanding JavaScript promise conceptually if someone tells you that the Promise is sort of like Java's Future is not hard. But I am not sure the high-level understanding is useful alone. There are many, many videos and articles that attempt to explain how to use Promise but when it clicked for me is when I asked the most amazing tool ever (it seems wrong to describe this miracle as merely a "tool" -- we can discuss my thoughts about Copilot in another article) about what the source for the Promise class looks like.

Copilot pointed out that the class for Promise is written in very sophisticated C++ code but Copilot produced pseudocode in a JavaScript-like language -- it is simplified but I think conveys the key ideas for really understanding how Promises work:

class Promise {
  constructor(executor) {
    // The "state" of the Promise: "pending", "fulfilled", or "rejected"
    this.state = 'pending';
    // The value of the Promise if it gets fulfilled
    this.value = undefined;
    // The reason for rejection if it gets rejected
    this.reason = undefined;

    // Define the `resolve` and `reject` functions that the executor will call
    const resolve = (value) => {
      if (this.state === 'pending') {
        this.state = 'fulfilled';
        this.value = value;
      }
    };

    const reject = (reason) => {
      if (this.state === 'pending') {
        this.state = 'rejected';
        this.reason = reason;
      }
    };

    // Call the executor function immediately, passing `resolve` and `reject`
    try {
      executor(resolve, reject);
    } catch (error) {
      // If the executor throws an error, reject the Promise
      reject(error);
    }
  }

  // Then method for chaining
  then(onFulfilled, onRejected) {
    // ...implementation details...
  }

  // Catch method for error handling
  catch(onRejected) {
    // ...implementation details...
  }
}        

I was astounded -- almost an audible "clicking sound" was the result of Copilot's brilliant response to my prompting.

Here are the key ideas:

  • reject and resolve are part of the Promise class itself -- maybe some wonder where these functions come from. Note that the arrow function has access to reject and resolve due to JavasScript's lexical scoping rules.
  • Invoking the constructor for a Promise causes the executor that is passed in to be invoked immediately.
  • A quote from Copilot: "So, it's not the Promise itself that's asynchronous, but rather the operations you perform within the executor function. The Promise simply provides a way to manage and interact with these asynchronous operations."

The executor must know how to properly use reject and resolve

And that is pretty much it. I will add an example Copilot provided:

new Promise((resolve, reject) => {
  // Start an asynchronous operation
  setTimeout(() => {
    // After 1 second, we resolve the Promise
    resolve('Operation completed');
  }, 1000);
});        

I am extremely interested in knowing whether this post helps anyone. I think, assuming it is helpful, a lot of time will be saved.

Ahmad Hussein

Operations Manager .Hospitals Management

4 个月

Amazingly beautiful

要查看或添加评论,请登录

社区洞察

其他会员也浏览了