Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Promise.resolve a asynchronous function?

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)

like image 871
Willem van der Veen Avatar asked Feb 11 '18 15:02

Willem van der Veen


People also ask

Is promise resolve asynchronous?

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.

Are promises asynchronous functions?

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.

Is promise asynchronous or synchronous?

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.

Are promises always asynchronous?

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.


1 Answers

 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.

like image 138
Jonas Wilms Avatar answered Sep 17 '22 12:09

Jonas Wilms