Whenever we create a new promise class, we would do something like this:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 4000)
});
promise.then((result) => console.log(result));
So, this is my way of thinking about how things work behind:
Promise
will have a constructor of an arrow function.setTimeout
will run theresolve('success')
function within the specified time limit, and returning aPromise
withresolved
state (which I think is another class because it has constructor)- The
then()
function will run whatever function passed on the first step (So in this case, the anonymous arrow function that returns the Promise)
First of all, why we can pass a resolve and use it as a function in setTimeout
? I thought we haven't even declared it yet and it's not the part of the window.
Second, can someone correct my way of thinking here (so maybe can help me explaining what is going on within the process)?