I just checked some details of this repo - faye, the author implemented the Promise in scratch which is impressed me. There are something confused me: in this line, calls
seems useless, just want to know if it is a trick for some asynchronous issues, or just a redundant declaration?
// L41 in src/util/promise.js
var execute = function(promise, task) {
if (typeof task !== 'function') return;
var calls = 0; // weird variable
var resolvePromise = function(value) {
if (calls === 0) resolve(promise, value);
};
var rejectPromise = function(reason) {
if (calls === 0) reject(promise, reason);
};
try {
task(resolvePromise, rejectPromise);
} catch (error) {
rejectPromise(error);
}
};
CodePudding user response:
It's being used to detect if you try to resolve or reject the promise multiple times. When you call these functions, it increments the count
variable, and then tests its original value. If the original value was 0
, this is the first time either of the functions was calls, so it continues and calls resolve()
or reject()
. Otherwise it just returns.
The logic is equivalent to this:
var execute = function(promise, task) {
if (typeof task !== 'function') return;
var firstTime = true;
var resolvePromise = function(value) {
if (firstTime) {
firstTime = false;
resolve(promise, value);
}
};
var rejectPromise = function(reason) {
if (firstTime) {
firstTime = false;
reject(promise, value);
}
};
try {
task(resolvePromise, rejectPromise);
} catch (error) {
rejectPromise(error);
}
};
CodePudding user response:
It really seems that calls is not doing anything, maybe they had a different implementation, but it ended up starting it at 0 and a meaningless variable was left.