preface

Xiaobian has written an article before:What about Promise in the front-end interview?Review the past and know the new

How to an article and promise again today, ha ha ha ha friends don’t hurry to leave, because met a to find internship students, had internships to find how to chat, let me the deepest impression is that she speak promise of interview questions, she said that after the side knew cool cool, and if have a chance to really want to and the interviewer says: Interviewer: Sorry! I finally got Promise!

I promise to make a promise. I promise to make a promise. Students to participate in a big factory interview, we look at the interview questions and students will know how uncomfortable the students.

The interview questions

  • CSS implements horizontal and vertical center
  • The attribute of the flex
  • The CSS Transition implementation and what properties it has
  • CSS to achieve 360 degrees along the Y axis rotation (direct self – explosion CSS not…. The hemp)
  • Okay, so what are the basic data types in JS
  • How to judge an array
  • Difference between reference types and primitive types
  • What is a stack? What is a heap?
  • Handwritten Flip String
  • Write “Sum (1,2,3)” in your hand. Write “Sum (1,2,3)” in your hand.
  • The difference between the arrow function and the normal function is that the arrow function is not the same as the normal function. The arrow function is the same as the normal function. Tears eye)
  • Array deduplication method
  • Lazy image loading
  • What is the cause of the cross domain, the same origin policy
  • Say what you know about the solution (JSONP and CORS only)
  • Cookie, sessionStorage, localStorage difference
  • What is the difference between GET and POST? What is the difference between GET and POST? What is the difference between GET and POST?
  • Ask about the project, React
  • Knowledge of ES6 (Promise was inevitable….)
  • Let var const
  • Do you know Promise? What is the understanding of Promise? The Promise object represents an asynchronous operation with three states, which transition to one way…
  • What problem is it designed to solve? (EMMM nested callbacks when an asynchronous return value had to wait for another async, and Promise solved the callback hell.)
  • So how does it solve callback hell? (Promise objects are internally synchronous, and are called when the internal value is obtained. Then can be used asynchronously. Then.
  • M: Well, then, then… So how does it implement always.then? Emmm… The.then chain call is… Uh, well…)
  • What are the methods in a Promise? What’s the difference between all and race
  • In particular,.catch() and reject (… I’m falling asleep…)

The end of the link

  • Ask the interviewer about the understanding of CSS (necessary but not important, the core of the front end is to try to restore the design draft one by one, only when the page is well written can you consider interaction)
  • How to learn (foundation is the most important, CSS and JS should pay attention to practice, building a house is the most important or the foundation, all the framework source code, components and so on are based on CSS and JS)
  • How did I go through this process (doing more projects, learning to understand every detail in the projects, again reminding me of the importance of the basics)

Summary of Promise

Promise is a new ES6 reference type that allows you to instantiate objects with new. Promise contains asynchronous operations inside.

new Promise(fn)

Promise.resolve(fn)

Both methods return a Promise object.

  • A Promise has three states: Pending, execution, and Rejected, and a Promise must be one of these states. It can only be the result of an asynchronous operation, which can determine the current state and cannot be changed by any other operation.
  • The state can only be changed from Pending to Fulfilling or from Pending to Rejected. Besides, the state will not change after the change and will always remain this state.
  • Pending will be a private value, while Pending will be the Rejected one. When the Promise reaches the Fulfilled or Rejected one, it will be a private reason. The asynchronous code executing receives the value or reason.

With this in mind, we can get the following code:

Realize the principle of

Class Promise {constructor() {this.state = 'pending'; this.value = 'undefined'; // This. Reason = undefined; }} Copy the code

Basic usage

The Promise state can only be operated on internally, which is performed in the Promise executor function. Promise must take as an argument a function called the executor function, which in turn contains the resolve and reject arguments, which are two functions.

  • Resolve: Fulfilling the state of the Promise object from Pending to successful
  • Reject: Reject the state of a Promise object from Pending(in progress) to Rejected(failed) and throw an error.

The use of chestnuts

let p1 = new Promise((resolve,reject) => { resolve(value); }) setTimeout(() => { console.log((p1)); // Promise {<fulfilled>: undefined} },1) let p2 = new Promise((resolve,reject) => { reject(reason); }) setTimeout(() => { console.log((p2)); // Promise {<rejected>: undefined}},1

Realize the principle of

  • P1 resolve is fulfilled, and the parameter value is accepted. The state change is fulfilled, which cannot be changed again.
  • P2 reject reject reject reject reject reject reject reject
  • If the executor function returns an error, reject is executed directly.

So you get the following code:

Class Promise{constructor(executor){constructor(constructor){this.state = 'pending'; This. value = undefined; // This. Reason = undefined; let resolve = value => { console.log(value); If (this. State === 'pending') {// Fulfill the state until it is fulfilled; this.state = 'fulfilled'; // Save the successful value this.value = value; }}; let reject = reason => { console.log(reason); If (this.state === 'pending') {// reject state to console. Log ('rejected state executed '); this.state = 'rejected'; // This. Reason = Reason; }}; // Reject (); // Reject (); // Reject (); } catch (err) { reject(err); }}} Copy code

Check the above code:

class Promise{... } new Promise((resolve, reject) => {console.log(0); SetTimeout (() => {resolve(10) // reject('JS I do not love you ') // reject('JS I do not love you ') // throw new Error(' JS I do not love you ') // throw new Error(' JS I do not love you ') // 3}, 1000)}
  • When code 1 is executed, the output is 0, and the output is 10 in one second and the fulfilled state is executed.
  • When executing code 2, the output is 0. A second later, the output is I do not love you and the rejected state is executed
  • It’s your fault to throw an error when executing code 3

Method. Then

promise.then(onFulfilled, onRejected)

  • When the Promise is initialized, the executor function has already changed the state of the Promise. And the executor functions are executed synchronously. The data returned by the asynchronous operation (the successful value and the reason for the failure) can be handed over to.then, providing a handler for the Promise instance.
  • Once the Promise instance is generated, you can use the Then method to specify callbacks for the Resolved and Rejected states, respectively. These two functions onFulfilled and onRejected are both optional and do not have to be provided. If provided, the Promise will be executed when it enters the Resolved and Rejected states, respectively.
  • Also, any non-function-type arguments passed to the Then method are silently ignored.
  • The Then method must return a new Promise object (key to implementing chained calls)

Realize the principle of

  • The Promise can only convert the final state once, so the operations for the onFulfilled and onRejected parameters are mutually exclusive
  • When the state is fulfilled, onFulfilled, pass in this. Value. OnRejected: Do not refute the rejected state unless you have rejected it
Class Promise {constructor(executor) {this.state = 'pending'; this.value = undefined; // This. Reason = undefined; This.onresolvedCallbacks = []; this.onresolvedCallbacks = []; this.onresolvedCallbacks = []; this.onresolvedCallbacks = []; this.onRejectedCallbacks = []; // Fulfill the performance of the async task. Fulfill the performance of the async task. Fulfill the function. This. Value = value this. State = 'fulfilled' / / onFulfilled to execute an enclosing onResolvedCallbacks. ForEach (fn = > fn ()); }} let reject = (reason) => {if (this.state === 'pending') {console.log('rejected '); this.reason = reason this.state = 'rejected' this.onRejectedCallbacks.forEach(fn => fn()); }} try {executor(resolve, reject)} catch (e) {reject(err)}} Turn over the control) then onRejected) { if (this.state == 'pending') { this.onResolvedCallbacks.push(() => { onFulfilled(this.value) }) this.onRejectedCallbacks.push(() => { onRejected(this.reason) }) } console.log('then'); (this. State == 'fulfiiied') {onFulfilled(this. Value); If (this.state == 'rejected') {onRejected(this.reason)}} let p1 = new Promise((resolve, reject) => { console.log(0); SetTimeout (() => {// resolve(10) reject('JS I do not love you ') console.log('setTimeout'); }, 1000) }).then(null,(data) => { console.log(data, '++++++++++'); }) copy the code
0 then rejected state is executed JS I do not love you ++++++++++ setTimeout copy code

When resolve is executed in a setomeout, state is still pending. We need to store both the success and the failure in their respective arrays at the time of the call to then. Whenever we reject or resolve, we will call them.

Now can implement asynchronously, but still can’t chain call ah? To ensure that the Then function is chained, the Then returns an instance of the Promise and passes the value returned by that Promise into the next Then.

Promise’s various methods

Promise.prototype.catch()

Catch an exception handler that handles the exception that may have been thrown in the previous callback. Only one parameter OnRejected handler is received. This calls Promise.prototype.then(null, OnRejected), so it returns a new Promise as well

  • For example,
let p = new Promise((resolve, reject) => { setTimeout(() => { resolve(10) }, 1000) }).then(() => { throw Error("1123") }).catch((err) => { console.log(err); }).then(() = console.log(' Continue after exception '); }) copy the code

Execution can continue after the first.then exception is caught.

Promise.all()

Promises created by promise.all () will be resolved once the set of promises has been resolved. This means that it waits for all Promise programs to return and then executes subsequent programs. Returns a new Promise.

  • For example,
let p1 = new Promise((resolve, reject) => { resolve('success1') }) let p2 = new Promise((resolve, reject) => { resolve('success1') }) // let p3 = Promise.reject('failed3') Promise.all([p1, p2]).then((result) => { console.log(result) // ['success1', 'success2'] }).catch((error) => { console.log(error) }) // Promise.all([p1,p3,p2]).then((result) => { // The console. The log (result) / /}). The catch ((error) = > {. / / the console log (error) / / / / / / 'failed3'}) duplicate code

From the above example, we can get the properties of all:

  • If all succeed, the return value of the synthesized Promise is an array of return values for all child Promises.
  • If there is a failure, the first failure will use its own reasons as the reason for failing to compose the Promise.

Promise.race()

Promise.race() is the first Promise to be resolved or rejected in a set of collections, returning a new Promise.

  • For example,
let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('success1') },1000) }) let p2 = new Promise((resolve, reject) => { setTimeout(() => { reject('failed2') }, 1500) }) Promise.race([p1, Then ((result) => {console.log(result)}). Catch ((error) => {console.log(error) // 'success1'})

From the above examples, we can get the properties of RACE:

  • In any case, the one that completes first executes the corresponding.then or.catch. Please click here to receive the 269-page Dachang front end exam information, including the interview questions related to Promise

conclusion

The Promise above concludes here and you can share your understanding in the comments section below.

The interview can let oneself discover more knowledge blind spot, thus promotes oneself study, everybody refuels together!!

Please don’t forget to comment on this article!!