preface
In the front of the cabbage also want to find an internship, so on the face. Let’s share all the questions first.
The interview questions
- The CSS is horizontally and vertically centered
- The attribute of the flex
- CSS Transition and its properties
- CSS rotation along the Y axis 360 degrees (directly self-destruct CSS not…. The hemp)
- Okay, so what are some basic JS data types
- How to determine the array
- The difference between reference types and primitive types
- What is a stack? What is a heap?
- Flip string by hand
- Write the argument of “Sum (1,2,3)” by hand.
- The difference between the arrow function and the normal function is the difference between the arrow function and the normal function. Tears eye)
- A method to remove the weight of an array
- Lazy loading of images
- What is cross-domain? What is the same origin policy
- Talk about solutions you know (just JSONP and CORS)
- Cookie, sessionStorage, localStorage
- The difference between get and POST is the difference between get and post.
- I asked about the project, React
- What you know about ES6 (Promise really can’t escape….)
- Let var const
- You know Promise? What’s your understanding of Promise? (Mention that the Promise object represents an asynchronous operation that has three states, and the state changes to one way…)
- So what kind of problem is it supposed to solve? (EMMM will nest callbacks when an asynchronous return value needs to wait for another asynchronous, and Promise can solve this callback hell problem.)
- So how does it solve callback hell? (The Promise object is internally synchronous, and will be called after receiving internal values. Then asynchronous operations can always be. Then.
- Okay, you said you could always. Then. Then… So how does it implement always.then? Emmm… This. Then chain call is… Well…)
- What’s the difference between “all” and “race”
- To be specific. Catch () and reject (… I’m numb…)
The end of the link
-
Asked the interviewer about 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 written can you consider interaction)
-
How to learn (foundation is the most important, CSS and JS to pay attention to practice, building a house is the most important or foundation, all the framework source code, components and so on are based on CSS and JS)
-
How did I get through this process (do more projects, learn to understand every detail in projects, remind me again about the importance of basics)
Summary of Promise
Promise is a new reference type in ES6 that allows you to instantiate objects with new. Promises contain asynchronous actions within them.
new Promise(fn)
Promise.resolve(fn)
Both methods return a Promise object.
- A Promise has three states: Pending, Fulfilled and Rejected. And the Promise must be one of the three states. Only the result of the asynchronous operation can determine which state it is in, and no other operation can change this state.
- The state can only change from Pending to depressing or from Pending to Rejected. After the state changes, it will not change again and will always remain in this state.
- When Pending changes to Fulfilled Promise, there will be a private value; when Pending changes to Fulfilled Promise, there will be a private reason. When the Fulfilled Promise reaches Fulfilled Promise or Fulfilled Promise, The executing asynchronous code receives either the value or reason.
With this in mind, we can get the following code:
Realize the principle of
class Promise {
constructor() {
this.state = 'pending' // Initialize the incomplete state
// Success value
this.value = undefined;
// Cause of failure
this.reason = undefined; }}Copy the code
Basic usage
The Promise state can only be manipulated internally, which is performed in the Promise executor function. A Promise must accept a function as an argument, which we call the executor function, which in turn takes resolve and reject, two functions.
- 1. Resolve: This will be a pity when the state of the Promise object changes from Pending to Fulfilled.
- Reject: Changes the state of the Promise object from Pending to Rejected and throws 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)
Copy the code
Realize the principle of
- P1 resolve is successful, parameter value is received, and the state changes to depressing, which cannot be changed again.
- P2 Reject: reject. The parameter Reason changes to Rejected and cannot be changed again.
- If the Executor executor function fails, execute reject.
So you get the following code:
class Promise{
constructor(executor){
// Initialize state to wait state
this.state = 'pending';
// Success value
this.value = undefined;
// Cause of failure
this.reason = undefined;
let resolve = value= > {
console.log(value);
if (this.state === 'pending') {
// State changes to a successful state after the resolve call
console.log('The state of being fulfilled');
this.state = 'fulfilled';
// Save the successful value
this.value = value; }};let reject = reason= > {
console.log(reason);
if (this.state === 'pending') {
// reject State changes to a failed state
console.log('Rejected state is executed');
this.state = 'rejected';
// Cause of storage failure
this.reason = reason; }};// If an error occurs, execute reject
try{
executor(resolve, reject);
} catch(err) { reject(err); }}}Copy the code
Check out the above code:
class Promise{... }// The above code
new Promise((resolve, reject) = > {
console.log(0);
setTimeout(() = > {
resolve(10) / / 1
// reject('JS I don't love you ') // 2
// There may be an error
// throw new Error(' it's your fault ') // 3
}, 1000)})Copy the code
- When code 1 is executed, the output is 0, and the output is 10 and the depressing state is executed one second later.
- When code 2 is executed, the output is 0 and the rejected state is executed after the output I love You again
- It is your fault to throw an error when executing code 3
Method. Then
promise.then(onFulfilled, onRejected)
- When a Promise is initialized, the executor function has already changed the state of the Promise. And the executor function is executed synchronously. The data returned by the asynchronous operation (the value of the success and the reason for the failure) can be handed over to.then processing, providing a handler for the Promise instance.
- After the Promise instance is generated, you can use the THEN method to specify the resolved and Rejected state callback functions, respectively. 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 state and the Rejected state respectively.
- And any non-function type arguments passed to the THEN method are silently ignored.
- The then method must return a new Promise object (the key to implementing chained calls)
Realize the principle of
- The Promise can only transform the final state once, so the operation of onFulfilled and onRejected parameters is mutually exclusive
- When the state is depressing, ondepressing will be executed and this.value will be passed. If the state is rejected, execute onRejected and pass this.reason
class Promise {
constructor(executor) {
this.state = 'pending' // Initialize the incomplete state
// Success value
this.value = undefined;
// Cause of failure
this.reason = undefined;
//. Then immediately after execution state is pengding. Then is saved
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
// Assign the asynchronous task to resolve
let resolve = (value) = > {
if (this.state === 'pending') {
console.log('The state of being fulfilled');
this.value = value
this.state = 'fulfilled'
// This will be fulfilled once
this.onResolvedCallbacks.forEach(fn= >fn()); }}let reject = (reason) = > {
if (this.state === 'pending') {
console.log('Rejected state is executed');
this.reason = reason
this.state = 'rejected'
this.onRejectedCallbacks.forEach(fn= >fn()); }}try {
executor(resolve, reject)
}
catch (e) {
reject(err)
}
}
// After a promise is resolved (complete the state transition, hand over control)
then(onFulfilled, onRejected) {
if (this.state == 'pending') {
this.onResolvedCallbacks.push(() = > {
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(() = > {
onRejected(this.reason)
})
}
console.log('then');
// This is a big pity. The implementation power will be transferred after the successful callback is passed in
if (this.state == 'fulfiiied') {
onFulfilled(this.value);
}
// The status of rejected fails is passed to the failed callback to transfer the execution authority
if (this.state == 'rejected') {
onRejected(this.reason)
}
}
}
let p1 = new Promise((resolve, reject) = > {
console.log(0);
setTimeout(() = > {
// resolve(10)
reject('JS I don't love you anymore. ')
console.log('setTimeout');
}, 1000)
}).then(null.(data) = > {
console.log(data, '+ + + + + + + + + +');
})
Copy the code
0Then rejected JS I don't love you ++++++++++setTimeout
Copy the code
When resolve is set in setTomeout, and then is state or Pending, we need to store success and failure in each array when we call THEN, reject or resolve when we call them.
Now you can do it asynchronously, but you still can’t do it chained? To ensure that the THEN function is chain-called, then needs to return a promise instance and pass the promise value into the next THEN.
Chain call and subsequent implementation of the source code
I don’t know this part either. I don’t understand it yet. More later. First paste the code:
class Promise{
constructor(executor){
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
let resolve = value= > {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onResolvedCallbacks.forEach(fn= >fn()); }};let reject = reason= > {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn= >fn()); }};try{
executor(resolve, reject);
} catch(err) { reject(err); }}then(onFulfilled,onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value= > value;
onRejected = typeof onRejected === 'function' ? onRejected : err= > { throw err };
let promise2 = new Promise((resolve, reject) = > {
if (this.state === 'fulfilled') {
setTimeout(() = > {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch(e) { reject(e); }},0);
};
if (this.state === 'rejected') {
setTimeout(() = > {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch(e) { reject(e); }},0);
};
if (this.state === 'pending') {
this.onResolvedCallbacks.push(() = > {
setTimeout(() = > {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch(e) { reject(e); }},0);
});
this.onRejectedCallbacks.push(() = > {
setTimeout(() = > {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch(e) { reject(e); }},0)}); }; });return promise2;
}
catch(fn){
return this.then(null,fn); }}function resolvePromise(promise2, x, resolve, reject){
if(x === promise2){
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called;
if(x ! =null && (typeof x === 'object' || typeof x === 'function')) {
try {
let then = x.then;
if (typeof then === 'function') {
then.call(x, y= > {
if(called)return;
called = true;
resolvePromise(promise2, y, resolve, reject);
}, err= > {
if(called)return;
called = true; reject(err); })}else{ resolve(x); }}catch (e) {
if(called)return;
called = true; reject(e); }}else{ resolve(x); }}/ / resolve method
Promise.resolve = function(val){
return new Promise((resolve,reject) = >{
resolve(val)
});
}
/ / reject method
Promise.reject = function(val){
return new Promise((resolve,reject) = >{
reject(val)
});
}
/ / race method
Promise.race = function(promises){
return new Promise((resolve,reject) = >{
for(let i=0; i<promises.length; i++){ promises[i].then(resolve,reject) }; })}//all (get all promises, execute then, place the results in an array, and return them together)
Promise.all = function(promises){
let arr = [];
let i = 0;
function processData(index,data){
arr[index] = data;
i++;
if(i == promises.length){
resolve(arr);
};
};
return new Promise((resolve,reject) = >{
for(let i=0; i<promises.length; i++){ promises[i].then(data= >{
processData(i,data);
},reject);
};
});
}
Copy the code
Interested partners can move
reference
Promise’s various methods
Promise.prototype.catch()
Catch an exception handler that handles any exceptions that might have been thrown in a previous callback. Only the onRejected handler is accepted. This is equivalent to calling promise.prototype. then(null,onRejected), so it will also return a new Promise
- chestnuts
let p = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve(10)},1000)
}).then(() = > {
throw Error("1123")
}).catch((err) = > {
console.log(err);
})
.then(() = > {
console.log('Exception catch can continue. Then');
})
Copy the code
Execution can continue after the first. Then exception is caught.
Promise.all()
Promise.all() creates promises that are resolved when the set of promises is resolved. That is, it waits for all promise programs to return results and then executes subsequent programs. Return a new Promise.
- chestnuts
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) => {
// console.log(result)
// }).catch((error) => {
// console.log(error) // 'failed3'
//
// })
Copy the code
All has the properties described above:
- If all succeed, the return value of the synthesized Promise is the array of return values of all the child Promises.
- If there is a failure, the first person to fail will use his or her own reasons as the reason for the failure of the composite Promise.
Promise.race()
Promise.race() is the first Promise resolved or rejected in a set of sets, returning a new Promise.
- chestnuts
let p1 = new Promise((resolve, reject) = > {
setTimeout(() = > {
resolve('success1')},1000)})let p2 = new Promise((resolve, reject) = > {
setTimeout(() = > {
reject('failed2')},1500)})Promise.race([p1, p2]).then((result) = > {
console.log(result)
}).catch((error) = > {
console.log(error) // 'success1'
})
Copy the code
Have the chestnut obtained above, the nature of race:
- Anyway, the first one that completes, the corresponding.then or.catch. Who calls who first
conclusion
The Promise above is summarized here, it may not be too clear, interested partners can look at the link, you can also understand what you can exchange and learn in the comments section below.
At the end of the interview, the interviewer was very nice and we had a very happy conversation. I could probably say a little bit about all the questions, but I always forgot the key parts of HHHHHH. At the end of the conversation with the interviewer, I was easy to forget this question, haha, he said that I forgot because I did not learn, so I still need to summarize more and do more projects in the future.
Interview can let oneself discover more knowledge blind spot, thus promote oneself study, everybody refuels together blunt!!