I'm reading through this article on the inner workings of a promise
. To do that, the author showcases a simplified implementation of a promise
working properly.
The code is as follows:
class PromiseSimple {
constructor(executionFunction) {
this.promiseChain = [];
this.handleError = () => {};
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
executionFunction(this.onResolve, this.onReject);
}
then(onResolve) {
this.promiseChain.push(onResolve);
return this;
}
catch(handleError) {
this.handleError = handleError;
return this;
}
onResolve(value) {
let storedValue = value;
try {
this.promiseChain.forEach((nextFunction) => {
storedValue = nextFunction(storedValue);
});
} catch (error) {
this.promiseChain = [];
this.onReject(error);
}
}
onReject(error) {
this.handleError(error);
}
}
And it is called as such, just like a regular promise
:
// Assume this is your AJAX library. Almost all newer
// ones return a Promise Object
const makeApiCall = () => {
return new PromiseSimple((resolve, reject) => {
// Use a timeout to simulate the network delay waiting for the response.
// This is THE reason you use a promise. It waits for the API to respond
// and after received, it executes code in the `then()` blocks in order.
// If it executed is immediately, there would be no data.
setTimeout(() => {
const apiResponse = fakeApiBackend();
if (apiResponse.statusCode >= 400) {
reject(apiResponse);
} else {
resolve(apiResponse.data);
}
}, 5000);
});
};
I'm having a hard time grasping the following:
Why do lines
6
and7
of thePromiseSimple
class exist? I'm trying to understand the point of bindingthis.onResolve
tothis
. Isn't it already bound to the properthis
context?I don't understand why this implementation doesn't block the main thread. No where in the
PromiseSimple
class does it offload the work onto another thread or anything of the sort. But surely enough, if I put aconsole.log(...)
statement at the very end of my program, thatconsole.log(...)
statement would be printed out as the first thing I'd expect it to, like a regularpromise
. I figured it'd be paused until the fakemakeApiCall
function had finished since this isn't a true implementation of apromise
.
I want to grasp this but I'm just not getting how this mini implementation allows the proper promise
behavior that we're used to. Any help is greatly appreciated.
Update
A recommendation of making this a duplicate has been proposed but I want to elaborate why they are not the same. The duplicate question is more high level theory of why async calls are needed. I understand their use, and importance, and the various ways they're implemented. I'm looking to understand under-the-hood how they work.