0

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)

kd8
  • 53
  • 6
  • 1
    The names of the parameters can be anything, `resolve` and `reject` are the conventional names that describe what they do. – Barmar Mar 28 '23 at 21:17
  • 2
    Whatever you call them, the first is used to resolve the promise, the second is used to reject it. – Barmar Mar 28 '23 at 21:18
  • 2
    "execute if resolve returns true" -- that's not quite right. `.then()` is going to execute if you call `resolve()`, `.catch()` will be executed if you call `reject()`. – Barmar Mar 28 '23 at 21:21
  • 1
    The callback in the Promise constructor is for you to define. It only tells that whatever callback you come up with, the promise constructor will invoke that callback with two function parameters. It's up to you to name the function parameters. Convention is `resolve` and `reject` but i mostly name them as `v` and `x`. So if you invoke the first one with whatever name you had chosen, it resolves the promise and the second one rejects. – Redu Mar 28 '23 at 21:50
  • From what I gathered, there is a positional constraint JavaScript uses to differentiate the parameters, which are actually callback functions themselves. Furthermore, the `resolve()` and `reject()` are built-in JavaScript functions, hence why there were no definitions in the code to be studied. – kd8 Mar 28 '23 at 22:34

0 Answers0