Front-end interview-js binding-async await and promise

  1. How does js implement binding?
  2. Browser caching mechanism?
  3. The difference between session and cookie?
  4. Promise understand?
  5. Continuing from the previous question, what is the difference between async await and promise?
  6. Do you understand macro tasks and micro tasks? What is the task of promise, what about settimeout?
  7. Common http status codes, let’s talk about them in groups, and what status codes have you used?
  8. css weight?
  9. box model, flex box
  10. Handwritten code question: css centered
  11. What is the difference between http and https?

01How does js implement binding?

You can use the applay, call, and bind methods to implement the binding of this

The first parameter of apply() is null. In non-strict mode, when the first parameter is null or undefined, it will be automatically replaced with a pointer to the global object. The second parameter of apply() is an array or a class array.

This method will be executed immediately when the function is borrowed,

var max = Math.max.apply(null, [1, 2, 3, 4, 5]);
console.log(max); // 输出5

call() is the grammatical sugar of apply. It has the same function as apply() and can also implement inheritance. The only difference is that call() receives a parameter list, while apply() receives a parameter array.

var max = Math.max.call(null, 1, 2, 3, 4, 5);
console.log(max); // 输出5

The function of bind() is the same as that of call() and apply(). They can change the runtime context of the function. The difference is that call() and apply() will be executed immediately after calling the function, while the bind() method calls and changes the function. After the runtime context, return a new function for us to call when we need it.

var person = {
    
    
  name: 'person',
  getName: function() {
    
    
    return this.name;
  }
}
var boy = {
    
    
   name: 'oldCode'
}
// bind()返回一个新函数,供以后调
var getName = person.getName.bind(boy);

// 现在调用
console.log(getName());    // 输出oldCode

02 Browser caching mechanism

Browser caching is mainly divided into two categories: strong caching and negotiation caching

Strong cache
When the browser initiates an http request, the first thing to check is the strong cache. In this cache mechanism, there is no need to send a request, and it is mainly realized by carrying field confirmation

If the strong cache fails during the check, a request will be initiated to enter the negotiation cache.

Negotiation cache
After the strong cache fails, the browser will carry the cache tag in the request header to initiate a request to the server, and the server will judge whether to use the cache according to the tag value, and the tag field is divided into Last-Modified and Etag

Cache location
There are four browser cache locations, which are as follows in terms of priority:

  • Service Woker
  • Memory Cache
  • Disk Cache
  • Push Cache

Service Worker

It makes Js run outside the main thread. Although it is separated from the browser and cannot access dom elements, it can realize offline caching, message push, etc. Among them, offline caching refers to Service Woker Cache, and it is also an important part of PWA implementation. mechanism.

Memory Cache
refers to the memory cache. Its efficiency is the fastest, but its life cycle is very short. When the rendering process ends, it ceases to exist.

Disk Cache
refers to hard disk cache. Its access efficiency will be slower, but its storage capacity and storage time are relatively advantageous.

03What is the difference between session and cookie?

cookie:
In a website, http requests are stateless. That is to say, even after connecting to the server for the first time and logging in successfully, the second request server still cannot know which user the current request is. The emergence of cookies is to solve this problem. After the first login, the server returns some data (cookie) to the browser, and then the browser saves it locally. When the user sends the second request, it will automatically save the data from the last time. The cookie data stored in the request is automatically carried to the server, and the server can determine which user is the current user through the data carried by the browser. The amount of data stored in cookies is limited, and different browsers have different storage sizes, but generally no more than 4KB. Therefore, only a small amount of data can be stored using cookies.

session:

The role of session and cookie is somewhat similar, both to store user-related information. The difference is that the cookie is stored in the local browser, while the session is stored in the server. The data stored on the server will be more secure and not easy to be stolen. However, storing on the server also has certain disadvantages, that is, it will occupy the resources of the server, but now that the server has been developed, some session information is more than enough.

the difference

  • The cookie data is stored on the client's browser, and the session data is stored on the server
  • Cookies are not very safe. Others can analyze the cookies stored locally and cheat them. If security is the main consideration, session should be used.
  • The session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server. If the main consideration is to reduce server performance, you should use COOKIE
  • The data saved by a single cookie is <=4KB, and a site can save up to 20 cookies. There is no upper limit for the session, but for the sake of server-side performance, do not store too many things in the session, and set the session deletion mechanism.
  • Store important information such as login information as SESSION; if you need to keep other information, you can put it in COOKIE

04 Do you understand the promise?

Promise is a solution for asynchronous programming: it represents the final state of an asynchronous operation and the returned value;

In essence, it is a promise that it will give you a result after a period of time.

Promise has three states: pending (waiting state), fulfilled (successful state), rejected (failed state); once the state changes, it will not change again. Once a promise instance is created, it is executed immediately.

Usage of promise:

A Promise must provide a then method to access its current value, future value, and reason.

The promise.then(onFulfilled, onRejected) callback function can only be executed once and returns a promise object

Each operation of Promise returns a Promise object, which supports chain calls.

The callback function is executed through the then method, and the callback function of Promise is a micro-queue placed in the event loop.

function fn(){
    
    
     return new Promise((resolve, reject)=>{
    
    
         成功时调用 resolve(数据)
         失败时调用 reject(错误)
     })
 }
 fn().then(success, fail).then(success2, fail2)
Promise.all 用法

The **Promise.all()** method is used to wrap multiple Promise instances into a new Promise instance.

Both promise1 and promise2 succeed to call success1

Promise.all([promise1, promise2]).then(success1, fail1)

Promise.race Usage

The Promise.race() method also wraps multiple Promise instances into a new Promise instance.

Promise1 and promise2 will call succ ess1 as long as one of them succeeds

promise1 and promise2 will call fail1 as long as one of them fails;

In short, whoever succeeds or fails first is considered the success or failure of the race.

 Promise.race([promise1, promise2]).then(success1, fail1)

Disadvantages of promise: cannot be canceled,

05 What is the difference between async await and promise?

Promise is a solution to asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events. Simply put, Promise is like a container, which stores some future execution (asynchronous) The result of the event, and once these results are generated, they cannot be changed.
Async and await are also a solution for asynchronous programming. It follows the syntactic sugar of the Generator function. It has a built-in executor, which will be executed automatically without additional calls And output the result, it returns a Promise object.

Using the async function can make the code much more concise. You don’t need some then like Promise, you don’t need to write anonymous functions to handle the resolve value of Promise, you don’t need to define redundant data variables, and you don’t need to nest code.
The difference between the two.
The appearance of Promise solves the "regional callback" problem caused by the traditional callback function, but its syntax leads it to develop vertically and form a callback chain. When encountering complex business scenarios, such syntax is obviously not suitable. beautiful. The async await code looks more concise, making asynchronous code look like synchronous code. The essence of await is to provide syntactic sugar equivalent to the "synchronous effect" of waiting for asynchronous return capabilities. Only after this line of code is executed will it be executed next sentence.

async await, like Promise, is non-blocking.

Async await is implemented based on Promise, which can be said to be an improved version of Promise, which cannot be used for ordinary callback functions.

All the interview questions and answers are organized into this official account, welcome to communicate together
insert image description here

Guess you like

Origin blog.csdn.net/buruyang/article/details/112297280