In the following code how does JavaScript determine that the state of myPromise has become "fulfilled"? I.e., how is the determination made that it's time to put the .then() handler into the microqueue for subsequent execution?
const myPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Resolved promise: ');
}, 2000);
});
myPromise.then((resolvedValue) => {
console.log(resolvedValue + 'The .then() handler is now running');
});
// Output (after ~2 seconds): "Resolved promise: The .then() handler is now running"
Answer
You calling the function resolve changes the state of the promise, thus JS can know that the promise's state has changed by you calling resolve.
The callback attached to that promise with .then() will then be known to be scheduled (as a microtask).
Explaining your code
You instantiate a new Promise and provide a callback that is run immediately. The callback schedules a task to run after 2000ms. That task will resolve the promise upon execution.
After having constructed the promise, you then attach a callback via .then() to the returned promise. This will only execute once the promise has fulfilled.
Now your synchronous code has run to completion, so the event loop has time to execute another task. The next task may be the one after 2000ms, which resolves the promise (and therefore sets its state to "fulfilled").
Once the task to resolve the promise has finished executing, a microtask will be scheduled to run immediately after: That microtask will run the .then() callback. This will finally log your string.
Related
in this diagram is says that the event Loop will run the I/O callbacks (the axios request), then the check phase (setImmediate), but when i tested this, it was the opposite, i need explanation of the execution of that code.
console.log('first'); // logs instantly
setImmediate(() => console.log('immediate')); // will be executed in the next iteration of the event loop.
new Promise((resolve) => { // starts in promise in pending state
console.log('insidePromise');
const data = 'Promise';
resolve(data);
}).then((d) => console.log(d)); // prints after Promise is resolved
Output -
first
insidePromise
Promise
immediate
When the Promise is called it starts in a pending state and waiting for resolve.
setImmediate - triggers here before resolve is processed as setImmediate will have to be executed in the event loop.
https://nodejs.dev/learn/understanding-javascript-promises
Once a promise has been called, it will start in a pending state. This means that the calling function continues executing, while the promise is pending until it resolves, giving the calling function whatever data was being requested.
https://nodejs.dev/learn/understanding-setimmediate
Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the event loop.
I'm pretty new to JavaScript (using Node.js) and still learning. I try to wrap around my head with promises and I got into this situation where I don't understand if there is a difference between this code:
promiseFunc().then(() => {
anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
});
doSmthElse()
and this code:
promiseFunc().then(async () => {
await anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
});
doSmthElse()
If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before anotherPromiseFunc() is executed? So in order to prevent that, I have to add async/await? Or all code in .then() block is being waited to execute anyway before doing something else?
Note 1: I don't want to chain those promises, because there is more code in my case, but I just simplified it here.
Note 2: I don't use catch because if error will rip through I will catch it later.
If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before AnotherPromise() is executed?
doSmthElse() is guaranteed to be executed before anything in the fulfillment handler¹ is executed. Promise fulfillment and rejection handlers are always invoked asynchronously. That's true whether you declare the handler function using async or not.
For example:
console.log("before");
Promise.resolve(42)
.then(result => {
console.log("within", result);
});
console.log("after");
The output of that is:
before
after
within 42
So in order to prevent that, I have to add async/await?
Where you've added async/await in your example doesn't change when doSmthElse() is executed.
If you want doSmthElse() to wait until the promise has been fulfilled, move it into the fulfillment handler.¹
If your code were inside an async function, you could use await instead, like this:
// Inside an `async` function
await promiseFunc().then(() => {
anotherPromiseFunc();
});
doSmthElse()
That would do this:
Call promiseFunc() and get the promise it returns
Hook up a fulfillment handler to that promise via then, returning a new promise; that new promise is the operand to await
Wait for the promise from #1 to settle
When it does, your fulfillment handler is executed and runs anothterPromiseFunc() but doesn't wait for the promise it returns to settle (because, as you said, you're not returning that promise from the fulfillment handler).
At this point, the promise from #2 is fulfilled because your fulfillment handler has (effectively) returned undefined, which isn't a thenable (loosely, a promise), so that value (undefined) is used to fulfill the promise from #2.
Since the promise from #2 has been fulfilled, await is satisfied and doSmthElse() is executed.
¹ the function you pass then as its first argument
I assume that Promise() just stands for some function call returning a Promise:
You could say that .then registers an event listener that runs as soon as the promise settles => the task is finished. It still runs asynchronously So in your example doSmthElse will still run even if the promise hasn't been settled (so if the promise doesn't settle immediately doSmthElse will be called before the function inside .then)
To let your code run "in order". You would have to use await to ensure that doSmthElse is called after the promise settled or you could put doSmthElse into the .then block.
I'm trying to figure out how promises are handled in the runtime environment. Are they moved into the web API container until they resolve and then pushed into the callstack when .then is called? Here is some example code. Console.log runs before the promises which leads me to believe somewhere along the way they end up in the queue. I also noticed I can put a function in a .then and the returned promise will fill that functions parameters.
// asynchronous test
let promiseWhatever = new Promise( function(resolve, reject){
// variable to be chained later and passed in function argument
let chainedVariable = 'I am chained';
resolve(chainedVariable);
reject('rejected promise');
});
let promiseMe = function(promiseResult) {
let message = `${promiseResult} to my computer`;
return Promise.resolve(message);
// resolves here to be passed onto the second chained then
};
function hello() {
promiseWhatever
.then(promiseMe)
// how does promiseMe take in the result for its argument?
// then returns another promise and you can chain them
.then( function(fulfilled){
console.log(fulfilled);
}) // is fullfilling the code to display the string to the console.
.catch( function(err) {
console.log(err);
});
console.log('hello'); // logs first to the console
};
hello();
First off a promise is just a notification scheme. The underlying asynchronous operation (whatever code resolves or rejects the promise) that would typically be outside of Javascript (using native code) such as an incoming webSocket message or an ajax response or something like that.
All promise engines use the event queue. When a promise is resolved, they post an event to the event queue in order to trigger the appropriate .then() or .catch() handler to be called. It is not required by the language or promise specification, but a number of implementations use a special event queue for promise callbacks that is checked along with other types of event queues.
It is required by the promise specification that a .then() or .catch() handler is always called asynchronously AFTER the current event loop code has finished even if the promise is resolved immediately. That's why your console.log('hello') shows before the console.log() inside the .then() handler. This is by design and is done in order to create consistency on when a promise calls it's handlers (always after the current event loop code completes).
Are they moved into the web API container until they resolve and then pushed into the callstack when .then is called?
When a promise is resolved an event is inserted into the event queue which will cause the appropriate .then() callbacks to get called after the current event loop code has completed (on a future event loop cycle).
It's not clear what you mean by "web API container" so I can't comment on that.
I also noticed I can put a function in a .then and the returned promise will fill that functions parameters
Yes, this is how promises work. A .then() handler is passed a single argument that represents the resolved value of the promise. A .catch() handler is passed a single argument that represents the reject reason.
I've tried to understand Promise
from google source, and haven't found how it execute code asynchronously.
My understanding of asynchronous function is that code below it can be resolved at a time before it.
For example:
setTimeout(()=>{console.log("in")}, 5000);
console.log("out");
// output:
// out
// in
The second line fufilled before the first line , so I think setTimeout is an asynchronous tech. But see this code of Promise:
let p = new Promise((resolve, reject)=>{console.log('in'); resolve(1);});
console.log("out");
//in
//out
This code block is actually excuted line by line, if console.log('in'); is a time-consuming operation, the second line will be blocked until it's resolved.
We usually use Promise like this:
(new Promise(function1)).then(function2).then(function3)
Does this mean: Promise is just used to promise that function2 is executed after function1, it's not a tech to realize asynchronous ,but a method to realize synchronous (function1, function2, function3 are executed sequently).
A promise is just a way to describe a value that does not exist yet, but will arrive later. You can attach .then handlers to it, to get notified if that happens.
Does this mean: Promise is just used to promise that function2 is executed after function1?
Yes exactly, even if function1 returns it's value asynchronously (through a Promise), function2 will run only if that value is present.
it's not a tech to realize 'asynchronous' but a method to realize 'synchronous' [execution] ?
Not really. It makes little sense to wrap a value that already exists into a promise. It makes sense to wrap a callback that will call back "asynchronously" into a promise. That said, the Promise itself does not indicate wether the value it resolves to was retrieved in a synchronous or asynchronous maner.
function retrieveStuffAsynchronously() {
// direclty returns a Promise, which will then resolve with the retrieved value somewhen:
return new Promise((resolve, reject) => {
// directly executes this, the async action gets started below:
setTimeout(() => { // the first async code, this gets executed somewhen
resolve("the value"); // resolves asynchronously
}, 1000);
});
}
console.log(retrieveStuffAsynchronously()); // does return a promise immeadiately, however that promise is still pending
retrieveStuffAsynchronously().then(console.log);
Sidenote: However, Promises are guaranteed to resolve asynchronously:
const promise = new Promise((resolve, reject)=>{
console.log('one');
resolve('three');
});
promise.then(console.log); // guaranteed to be called asynchronously (not now)
console.log("two");
I have read on multiple websites, that the .then() method from the promise.prototype returns a promise. Unfortunately, no source describes the reason behind this.
The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. - developer.mozilla.com
Why/When would someone need this returned promise object, how is this promise object related to the original object.
Thanks a lot for helping.
A promise is executed asynchronously, you never know when the then() will be executed.
And a promise can return a promise, this allows you to chain asynchronous events handling in singles lines of code.
Example code given by Mozilla:
doSomething().then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
It avoids the "pyramid of doom" :
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
There are three main aspects to the fact that .then() returns a promise.
The first is that you can chain operations like this:
a().then(b).then(c).then(d)
Because .then() returns a new promise, the following .then() handlers will not be executed until that new promise resolves. If b and c are synchronous, then that new promise will resolve when they return and the chain will continue when first b is done and then when c is done.
The second is that the new promise can be influenced by what the .then() handler returns. This allows b, c and d to be asynchronous operations that, themselves returns promises and the chain will be sequenced appropriately. So, imagine that b and c both return promises themselves.
First you get a() returning a promise. When that resolves resolves, its .then() handler gets called. That will then run b. If b() is also an async operation and it returns a new promise, then the promise that a.then(b) returns that all the other .then() handlers are linked to will NOT be resolved until that new promise that b returned is resolved. This allows a .then() handler to insert a new asynchronous item into the chain. This is a very important aspect of chaining promises. .then() handlers can insert them own asynchronous operations into the chain and they can even do it conditionally based on prior results or current state.
If a().then(b) just returned the same promise that a() returns, then all the subsequent .then() handlers would not be able to "wait" for the promise that b() returns because they would have been linked to the a() promise and it has already resolved. It is the returning of this new promise that allows the function inside the .then() handler to influence the subsequent chain because that new promise is influenced by what the .then() handler returns.
The third aspect is that the return value of the .then() handler can influence the resolved value of the new promise and that is what is passed to the next .then() handler in the chain. If a().then(b) just returned the same promise that a() returns, then all the subsequent .then() handlers would just see the same resolved value from a() because that resolved value was already set when a() resolved which is before a().then() has called its .then() handler. These subsequent .then() handlers wouldn't be able to inherit a new resolved value from then code inside the .then() handler.
Let's look at a specific scenario. I'll use a delay method as a simple example of a function that returns a promise that resolves in the future.
function delay(t, val) {
return new Promise(resolve => {
setTimeout(() => resolve(val), t);
});
}
Then, define several different async functions:
function a(val) {
return delay(100, val + 1);
}
function b(val) {
return delay(50, val + 10);
}
function c(val) {
return val * 100;
}
Now, put them all in a chain:
a(100).then(b).then(c).then(val => {
console.log("all done: ", val);
});
Here's what happens step by step:
a(100) is called. This calls delay (which sets a timer) and returns a promise which I will call a1_promise just for purposes of describing things here.
Then, because we're doing a(100).then(b), we take the return value from a(100) which is the a1_promise and call a1_promise.then(b). That stores away the b function as a .then() handler function to be called sometime in the future when a1_promise is resolved (not right now). That then returns a new promise which I will call a2_promise.
Then, because we're doing a(100).then(b).then(c), we take the return value from a(100).then(b) which is the a2_promise and call a2_promise.then(c). That stores away the c function as a .then() handler function to be called sometime in the future when a2_promise is resolved (not right now). That then returns a new promise which I will call a3_promise.
Then, because we're doing a(100).then(b).then(c).then(...), we take the return value from a(100).then(b),then(c) which is the a3_promise and call a3_promise.then(c). That stores away our last anonymous function as a .then() handler function to be called sometime in the future when a3_promise is resolved (not right now). That then returns a new promise which I will call a4_promise (which nobody uses).
Now we're done with synchronous execution. Note that a().then(b).then(c).then(...) was all executed synchronously. All three .then() methods have already been called on all the different promises. But, because NONE of the promises created here are yet resolved, none of the .then() handlers have actually been called yet. They've all just been stored away to be called in the future when the promises are resolved.
Now some time passes and the timer created inside of a() fires and resolves a1_promise. That then triggers a1_promise to call any .then() handlers it has and pass it the resolved value of the a1_promise which in this case will be 100 + 1 or 101. Since there is just one .then() handler on the a1_promise and it is the b() function, it will call b(101) now. Executing that will just return a new promise which b() created and returned. We will call that new promise b_promise. Inside the a1_promise() it knows that it created the a2_promise() when a1_promise.then() was previously called so it knows that when it executes that stored .then() handler and that .then() handler executes and returns a new promise, then it holds off on resolving the a2_promise that it created until thatb_promiseis resolved. In this way, you can see that further execution of the chain is now controlled by theb_promise, thus the code executing inb()and the promise is returned are inserted into thea().then().then().then()chain holding off future.then()handlers until theb_promise` is resolved.
Now some more time passes and the timer created inside of b() fires and resolves the b1_promise with a newly modified value of 101 + 10 which is 111. This tells the a2_promise that it can now resolve with that value.
The a2_promise can then call it's .then() handler and can execute c(111) which again just like in step 6 returns c_promise which is not yet resolved.
Some time passes and c_promise resolves with a value of 111 * 100 which is11,100. That tells thea3_promise` that it can now resolve with that value.
The a3_promise can then call it's .then() handler which is our arrow function at the end of the chain and we get a console.log() showing 11000 as the final value.
This is the good part of a Promisse.
You can chain a lot of methods where which one depends from a method result (in this case Promisse.resolve) above, for example. Like this