In a tutorial on Promise (https://www.youtube.com/watch?v=DHvZLI7Db8E&ab_channel=WebDevSimplified), there was the following:
let p = new Promise((resolve, reject) => {
let a = 1 + 1;
if (a == 2) {
resolve('Success');
} else {
reject('Failed');
}
})
p.then((message) => {
console.log("this is a success" + message);
}).catch((message) => {
console.log("this is an error" + message);
})
In the documentation for Promise, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise, scrolling down to the Constructor section, we have:
Promise()
Creates a new Promise object.
The constructor is primarily used to wrap functions that do not already support promises.
What I learned from the video is that the .then() is going to execute if resolve returns true and .catch() will be executed when the reject return true.
What I don't understand is that the Promise() takes a function as a constructor, but the parameters can be arbitrary (the documentation doesn't say we need to use resolve
and reject
), so how does JavaScript know that the semantics of the parameters?
Also, the fact that resolve()
and reject()
are being called indicates that they are actually callback functions, but I'm not seeing them defined anywhere?
(The same doubt remains after reading other tutorials: https://www.freecodecamp.org/news/javascript-es6-promises-for-beginners-resolve-reject-and-chaining-explained)