When I have the following code:
var promise1 = Promise.resolve([1, 2, 3]);
promise1.then((value) => {
console.log(value);
// expected output: Array [1, 2, 3]
});
console.log('end of script');
I know that end of script is returned earlier because the promise
is asynchronous. But at what point of execution does it become asynchronous?
Is Promise.resolve()
asynchronous?
Or is .then
asynchronous or even both functions?
Is there some other mechanism playing under the hood?
(was a hell to google because I get only results of the new async await
features)
Is Promise. resolve() asynchronous? Not usually. But yes, depending on what argument you call it with it sometimes does schedule the assimilation of a thenable for later.
Promises are the foundation of asynchronous programming in modern JavaScript. A promise is an object returned by an asynchronous function, which represents the current state of the operation.
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.
25.5.4 Promises are always asynchronous It states so via the following requirement (2.2. 4) for the then() method: onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
Promise.resolve([1, 2, 3]);
Is Promise.resolve() asynchronous?
No that's just a regular function call. It will return a result immediately.
Or is .then asynchronous or even both functions
No. Both aren't asynchronous in the sense that
promise1.then((value) => console.log(value));
will immediately return a new Promise for chaining.
However a Promise definitely resolves asynchronously, which means that the inner function (value => console.log(value)
) is called definitely after your whole synchronous code executed.
Is there some other mechanism playing under the hood?
Yes there is a "magic" event loop in the background which manages all the async events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With