The introduction of

Before you understand promise, you should understand the basics, which are computer principles, browser principles, and JS implementation principles

Computer Principles

process

Definition: A process is the smallest unit of CPU resource allocation — an independent resource

thread

Definition: A thread is the smallest unit of CPU scheduling — shared resources

Issues related to

  1. Chrome opens a new window, TAB page is a process or thread? Answer: process
  2. How do processes communicate (how do Windows communicate)? Answer: storage (localStorage and sessionStorage, cookie)
  3. What are the differences between different types of storage?
  4. Principles of browsers (Mostly middle and advanced management) Browsers have multiple threads in a process

Principles of browsers

GUI rendering engine

  1. Parse HTML, CSS, build DOM tree => Layout => Draw
  2. It is mutually exclusive with the JS engine. When executing the JS engine thread, the GUI will be pending, and the GUI will continue to be executed when the task queue is idle

JS engine thread

  1. Process JS and parse execution scripts
  2. Allocates, processes, and executes events to be executed, event queues
  3. Blocking GUI rendering

Timer trigger engine

  1. setTimeout,setInterval
  2. Receives timer tasks assigned by the JS engine and counts them
  3. After the processing is complete, the event triggering thread is sent to trigger

Asynchronous HTTP request threads

  1. Asynchronously perform request class processing, Promise/Ajax, etc
  2. Receives asynchronous HTTP requests allocated by the JS engine
  3. Listen for the callback and give it to the event-triggering thread to fire

Event triggering engine

  1. Received source: timer, asynchronous, user operation
  2. The callback events are added to the end of the task queue and returned to the engine

JS Execution Principle

Allocate memory

Execution stack

Interview question 1: Stack overflow => performance optimization Interview question 2: Array operation return value problem splice split… promise.all promise.race

Task queue macro task: macro: script, setTimeout and setInterval, micro I/O task: new promise {}. Then ()

Micro is micro, no micro is macro macro task always precedes micro task

1. Understand promises

Promise specification

A promise is an object or function that has a then method. A promise has three states

state
  1. Pending: Initial state – Can be changed
  2. This is a big pity: the final state is unchangeable
  3. Rejected: Indicates the rejected state
Change of state
  1. pending -> reslove(value) -> fulfilled
  2. pending -> reject(reason) -> rejected
Then method
  1. Parameters:onFulfilledonRejected(Both arguments must be functions; if not, they should be ignored.)
  2. onFulfilledandonRejectIs microtask (JS is a single thread, divided into synchronous task and asynchronous task, and asynchronous task also has priority, microtask refers to the high priority)
  3. The then method can be called multiple times, using an array to store multiple onFulfilled callback and onRejected callback
  4. The return value of the then method isThe new promiseOnFulfilled or onRejected returns the result as X, which is passedresolvePromiseTo parse the promisethis.resolvePromise(promise2, x, resolve, reject);

2. Make a promise one step at a time

  1. Class object and defines three states
  2. inconstructorTo set the initial state and define value and Reason
  3. Implement the resolve and Reject methods to change the state when it is pending
  4. inconstructorFn receives resolve and reject, and throws reject if an error is reported
  5. Implement the then method, which takes two arguments:then(onFulfilled, onRejected) {}
  6. Check the processing then parameters and determine whether onFulfilled and onRejected are functions. If they are not functions, return value or reason
  7. Define the return value (promise2) and call different functions based on the current promise state
  8. Set up a monitoring mechanism for the status. When the status becomes a pity or Rejected, then perform the callback
  9. Create two new arrays to store successful and failed callbacks, respectively, and then, if pending
  10. Implement getter and setter functions, assign status, and add a forEach line
  11. When ondepressing or onRejected throws exception E, promise2 refuses to perform and returns rejection cause E. (In this case, we need a manual catch code, reject when we encounter an error.)
  12. This will be run when onFulfilled or onRejected returns a value xresolvePromiseMethods. willrealOnFulfilled(this.value)Assign to x,this.resolvePromise(promise2, x, resolve, reject);
  13. Implement the resolvePromise method
  14. OnFulfilled and onRejected are micro tasks that execute functions wrapped with queueMicrotask
  15. Implementing catch methods

3. Understanding Iterator, Generator and Async

Iterator iterator
  1. Is a special kind of object. Each iterator object has a next method,
  2. Each call returns a loot object containing two values: value: the value of the current property; Done: Checks whether traversal is complete
The Generator Generator
  1. A generator is a function that returns an iterator using a new keywordyield, using function*
function* generator() {
    const list = [1, 2, 3];
    for (let i of list) {
        yield i;
    }
}
let g = generator();
console.log(g.next()); // {value: 1, done: false}
console.log(g.next()); // {value: 2, done: false}
console.log(g.next()); // {value: 3, done: false}
console.log(g.next()); // {value: undefined, done: true}
Copy the code
  1. Pay attention to
  • The function automatically stops executing after each yield statement until next() is called again;
  • The yield keyword can only be used within the generator; using it elsewhere causes the program to throw an error;
  • You can create generators through function expressions, but you cannot use arrow functions

    let generator = function *(){}

4. Questions you may encounter in the interview

  1. Why was the promise resolve output value undefined
const test = new MPromise((resolve, reject) => { setTimeout(() => { resolve(111); }, 1000); }).then((value) => { console.log('then'); }); setTimeout(() => { console.log(test); }, 3000).Copy the code

If there is no return in. Then, return undefined, so value is undefined

  1. Why print a promise in a catch callback that says the state is pending
const test = new MPromise((resolve, reject) => { setTimeout(() => { reject(111); }, 1000); }). The catch ((reason) = > {the console. The log (" error "+" reason); console.log(test) }); setTimeout(() => { console.log(test); }, 3000).Copy the code

A: The catch function returns a new promise function named test, which has not yet completed execution in the catch, so it is pending