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:
领英推荐
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.
Operations Manager .Hospitals Management
4 个月Amazingly beautiful