So I'm currently learning about promises in JavaScript, and I tried making my first promise and realized that it ran the setTimeout() even if I didn't call the promise to begin with, just by defining it, it ran by itself. This being postLogin.
const postLogin = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Token: 1234")
}, 2000);
});
^ This logs out "Token: 1234" without calling postLogin.then()
Where as this doesn't run until I call postLogin1.then(token => {console.log(token)});
const postLogin1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Token1: 1234");
}, 2000);
});
postLogin1.then(token => {console.log(token)});
Why is it that if I don't add "resolve" it runs the code without invoking it?
Promise constructors call the function you pass to them immediately. This is the case in both your examples.
If you have console.log inside that function, then it will call console.log. If you don't, then it won't. That's the key difference between the examples.
The then method just adds an event handler that will be called when the promise is resolved (or immediately if it has already been resolved).
If you have console.log in the then handler, then it will be called then the function resolves.
If you don't ever call resolve then it will never resolve. The function you pass to it is still called.