This is a 'why' question, not a suggestion. I know the following function is incorrect, but it helps to clarify my question: I want to know what is wrong with this view (i.e. what requirement of Promise I am missing here). Answers can help other like me to get out of confusion. Please provide an example where the following requirement of Promise
is necessary:
I (incorrectly) assumed Promises are for deferring execution of functions and assigning a chain of then & catch. I need to know the following: Why does JavaScript Promise uses (resolve, reject) instead of a parameter-less callback that returns or throws?
In a naive and incorrect view, the Promise
could have been used in a simpler way (without two arguments resolve
, reject
) like the following:
/*new*/ IncorrectPromise(()=>{
let x = Math.random()>0.5;
console.log('promise 1');
if (x) {
return 'head1';
} else {
throw new Error('tail1');
}
})
.then((d)=>{
console.log('.then() d=', d);
})
.catch( (ex) =>{
console.log('.catch() e=', ex.message);
});
Instead of the Promise's way:
new Promise( (resolve_, reject_) => {
let y = Math.random()>0.5;
console.log('promise 2');
if (y) {
resolve_('head2');
} else {
reject_(new Error('tail2'));
}
})
.then((d)=>{
console.log(' .then() d=', d);
})
.catch( (ex) =>{
console.log(' .catch() e=', ex.message);
});
i.e. when the control flow exits the body of the callback of the promise, resolve or reject are used based on whether the exit was caused by a return
or a throw
.
My question is, why promises use the current syntax? The answer will be an example which cannot be done with this (naive) function.
The above syntax can be easily emulated with the following definition (for simplicity, ignore the fact that IncorrectPromise
is not a constructor, hence does not need the new
operator):
function IncorrectPromise(callback) {
return new Promise( (res, rej) => {
try {
res( callback() );
} catch (err) {
rej(err);
}
});
}
What would have been the shortcoming of this simpler usage syntax? What was the intention of the designers or the Promise
to use (resolve, reject)?