1. Promise Basic concept



Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively.

2. State diagrams




3. FAQ (Interview Questions)


A) Can return be used instead of resolve?

I. No, chain call cannot be implemented, and does not comply with the specification. The following is an example:

ii.



Iii. Execution Results:



1. Can’t change state, 2. Can’t chain call


B) Throw or reject?



i.
As is shown in
:

ii.


Iii. Execution Results:


Iv.1. The Promise constructor, as well as the functions executed by then calls, can basically be thought of as a try… In a block of catch code, so the program itself does not terminate because of an exception even if a throw is used in such code. The Promise state does not change.


4. Promise execution time (interview questions)

A) Will the resolve code be executed?

I.,

Ii. Execution Results:

iii.

1. Resolve will place promise. then in the microtask queue when there is no Error, and the microtask queue will be executed when all macro tasks are completed.

2. When there is an Error, the code behind the Error will not be executed, but the result of the Promise is still a pity

B) When the Promise encounters setTimeout

i.

Ii. Execution Results:

iii.

1. Execution sequence: 1 => 2 => 4 (macro task ends) =>3 (micro task ends)

5. Async/await with Promise

A) To sum up: an await is a Promise. If it is not a Promise, and if it is not, then an await will be invalid.

I. Turn the regular callback into the Promise method

ii.

Iii. Convert promises to async/await

Here is a front-end interview information to give you, there is a need to collect and private letter can be free to get oh.

In this paper, from the WEB zoroastrianism light roof (https://web.xingruanedu.com)