Reputation: 33
I am learning Promise in JS and I have few queries related to it.
This is a code snippet I have,
var promise = new Promise(
(resolve, reject) => {
var data = 'resolve';
resolve(data);
console.log('promise executor');
});
setTimeout(
() => {
promise.then(
(data) => {
console.log(data);
});
promise.then(
(data) => {
console.log(data);
});
}, 2000);
The output comes as,
promise executor
resolve
resolve
From the above output, I understand that body of executor
has executed immediately during construction of Promise. Now, I have few doubts/queries as follows,
executor
's execution, resolve
was actually undefined. Still, the browser does not throw error and discards the call, how?resolve
function is set after a delay of 2 seconds. Still browser calls the function, though the executor
has already executed and data
variable has lost the life. How?resolve
also gives an output. Doesn't it have limitation in number of calls to .then()
?Upvotes: 3
Views: 1545
Reputation: 705
1.A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of 3 possible states:
Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
Rejected: onRejected() will be called (e.g., reject() was called)
Pending: not yet fulfilled or rejected
A promise is settled if it’s not pending (it has been resolved or rejected). Sometimes people use resolved and settled to mean the same thing: not pending. Once settled, a promise can not be resettled. Calling resolve() or reject() again will have no effect. The immutability of a settled promise is an important feature.
2 .The fact promises do not resolve immediately sometimes and defer sometimes means that the API is consistent. Otherwise, you get undefined behavior in the order of execution.
3.Once the promise gets resolved, .then
function gets called immediately so if for one promise you write n
number of .then
functions then all will get executed at same time with same data sent in resolve.
Upvotes: 1
Reputation: 370619
resolve
there is a natural parameter of the promise
constructor - it does exist. (Feel free to add in console.log(typeof resolve);
)data
variable doesn't really exist at that point, but the promise still has been resolved with that 'resolve'
value. So, further .then
s added to the promise will immediately run with that value..then
. Check out the docs if you want: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promisesUpvotes: 1