The front-end may interview report | Shanghai

create by db on 2020-5-14 22:37:37

Recently revised in 2020-6-8 22:29:17

preface

Hey, Backwave, have you set up your stall yet?

By June, the impact of COVID-19 was waning.

Although this year is doomed to be the world’s economic winter, but the stalls or to place, the interview is also to go.

First, let’s talk about my situation: coordinate Shanghai, three non-undergraduate (non-double first-class non-computer major), front-end old novice, small company, technology stack Vue + ElementUI. I was planning to jump ship after the New Year, but the epidemic forced me to the middle of the year. I began to prepare for the interview on May 1, and the main delivery channel was bosses. After nearly a month, I interviewed seven companies successively (not including telephone interview) and got three offers. Here to do an interview report, but also their own stage summary.

The body of the

Write down your interview experience and questions, and attach some of your answers. Please refer to it on demand.

Company A

Company Status:

giant

Let’s just say I’m a bit bold — I hit the new BAT on the head at the beginning. It was recommended by the headhunter. I made some preparations, but as expected, I still failed. One side is the video interview, the interviewer is very nice, will ask some questions according to the resume, the basic knowledge is more, to handwritten code! Write the code by hand! Write the code by hand!

Question:

  1. Three column layout implementation and pros and cons

  2. Text is displayed on one line/three lines

  3. Redraw and backflow

  4. Handwritten Fibonacci series and its optimization

  5. Look at the code output. What are macro tasks and microtasks, and what are they?

  6. Write javascript deepClone function deepClone

  7. This section describes the principles, advantages and disadvantages of two Vue routing modes

  8. Write a JS event binding function

  const Event = {
    on() {} / / binding
    off() {} / / unbundling
    trigger() {} // Triggers the event
};
Copy the code
  1. Write the deduplicate function
 const arr = [1.'1'.'1'.'NaN'.NaN.'NaN', {a: 1}, '{a: 1}', {a: 1}]
Copy the code
  1. Vue mixin/ custom instructions/V-if/diff algorithm

Results:

Hung up the

Harvest:

Due to the lack of preparation (I dish I don’t say), coupled with some knowledge usually did not seriously reserve, stumbled through most of the questions, asynchronous /mixin/diff and so on did not in-depth understanding, fortunately the interviewer is very nice, will guide you to think step by step – but still failed.

Lesson learned: Don’t just be a coder (CV engineer?) The basics are important, understanding is important, and the most important thing is to be able to say what you want clearly.

Company B

Company Status:

It is a business department of the outsourcing company, doing its own project, which requires the middle and senior front end to cooperate with the background to realize (there is no front end itself).

A:

Since the department didn’t have a front end, they borrowed a front end leader (estimated senior) from another department to be the interviewer. Maybe because I don’t know much about their project, I focus on the basics.

Question:

  1. Semantic HTML

  2. Range of new features

  3. Redraw and backflow

  4. Closures and their applications

  5. New ES6 features, asking for let, promise, class, etc

  6. Describes the WebPack configuration items

  7. All the sorting algorithms you know, and how they work

  8. Several ways to pass parameters to the Vue component

… There are a lot of apis for JS objects and so on

2:

After the first interview, I went straight to the second interview, where the interviewer was the architect of my department (very typical), and mainly talked about the project and solutions to some problems.

  1. Why change jobs

  2. Based on the project requirements, how to investigate the requirements, choose the appropriate framework and scheme, detailed process

  3. Why do technology test PMP(it is written on my resume, I care more about whether I can do technology realistically)

  4. What is the most difficult problem you have encountered at work

  5. Have you ever led a team

  6. Future career planning

HR:

Then I entered HR. HR is a little sister with a great figure (wearing a mask but not seeing her face).

  1. When can I start

  2. What are your salary expectations

… The saliva words

Results:

I got the offer, but the salary didn’t meet my expectations, so I turned it down

Harvest:

A very fruitful interview experience, increased my knowledge, but also gave me a certain confidence. After all, the interview is a two-way selection process. It is also a good experience to meet some worthy people and think about some questions that you have not thought about at ordinary times.

Company C

Company Status:

Small company, doing their own projects, there are two front-end (both very young), it is estimated to hire a front-end leader, but JD did not write

Interview:

The size of the company is more than ten people, the general manager sent the interview invitation on the boss, close to where I live, so it is still very interested. But I don’t know whether the leader is not there or for other reasons, I sent two children to be the interviewers.

The interview experience was not very good. They probably don’t have the experience, and they don’t have the questions they need to ask. Ask some words vague, and is to take some questions in the work to ask ideas…

Results:

Maybe we are not particularly satisfied with each other, no further

Harvest:

A bad interview experience.

Company D

Company Status:

Medium-sized companies, doing government projects

A:

It was also not a particularly pleasant interview experience.

The interview was scheduled for 2:00 p.m., and I arrived ten minutes early. Yet from the same block came 1 front end, 3 tests, 6 backends (a lot of pressure) – their HR had everyone on board at the same time? ! Then the front desk had everyone line up to get their personal information sheets and print out the interview questions on the spot… A wave of operation 20 minutes passed, and then half an hour to do the problem, finished waiting to be interviewed…

Until close to four o ‘clock I was told to interview – come here, just face – come out for an interview, good attitude. Then came the sleathing. HR took me to a small office with only one computer — interviewers were interviewing remotely. At that time, ten thousand grass mud horses ran through my heart… But it’s all here…

Question:

  1. Introduce yourself

  2. User login process and permission determination, user information storage

  3. Route redirect, how to refresh the page

  4. Introduce the usual work content and process

  5. Introduce your work experience

  6. I sent a closure problem to see the output

  7. Will React

  8. Is there anything you want to ask me

Tell HR after the first thing — if there is a second interview and you need to do it remotely, please call ahead and let me know (I’m so polite…)

2:

The second interview is a video interview at home after work in the evening (wechat group chat)

The interviewer was ten minutes late for 8:00. HR told me that it was an interview for the boss. I thought I would talk about the project, brag and talk about my ideal (I didn’t ask much about one side). As a result, I met a very down-to-earth boss.

Question:

  1. Talk about the types of box models and their differences

  2. Div is centered vertically

  3. How do I write a dragable div and drag it into other nodes

  4. Vue Life cycle

  5. Vue Route guard

  6. Vue components pass parameters

  7. Draw an adaptive layout of three rows and three columns on site

Results:

I got the offer, but I turned it down due to my feelings about the company and the distance to work

Harvest:

It’s a really weird interview experience. It’s informative.

Company E

Company Status:

Medium to large companies (heard the name of the kind), do internal projects, JD requires senior

Interview:

A comfortable interview (maybe I’m a masochist).

HR is a very handsome man (it is rare to find a very handsome man). There are a lot of people in the company and it is a little noisy. The interview took place directly at the little table at the door. The interviewer unexpectedly countryman, very fierce, ask of very detailed, from shallow to deep — basically made a comb to all front-end knowledge.

Question:

  1. Semantic HTML

  2. Some HTML5 tags used

  3. And import function and difference
  4. Box model classification and distinction

  5. Absolute positioning and relative positioning

  6. BFC defines/acts/triggers conditions

  7. The properties of the display

  8. Selector priority

  9. Three column layout

  10. ES6 syntax :promise/ arrow function /class

  11. Usage and scope of closures

  12. Prototype chain, the method of inheritance

  13. Asynchrony and its solutions, macrotasks and microtasks and their processes

  14. Cross domain

  15. Implementing deep copy

  16. Realize the promise

  17. The difference/status code of HTTP GET and POST

  18. HTTP GET and POST

  19. Vue lifecycle/Component communication/responsive implementation/Routing pattern/Routing guard

  20. Webpack packaging principles, common Loaders and plugins, and some common configurations

  21. Asynchronous operations for Node.js

  22. The understanding of the TypeScript

  23. Implementation of front-end microservices

  24. Have you ever led a team

  25. What are you best at

The first answer is basically ok, but when it comes to webpack, Node, microservices, there are some difficulties. But the interviewer is very patient, every answer is a record, not clear is also very patient explanation. After communication, it was found that he met many people these days…

On the one hand, the interviewer gave me a good evaluation (maybe a bonus from my hometown), but I was regrettably informed that the interviewer did not have time for the second interview.

Results:

Hung up the

Harvest:

A very fruitful interview, the interviewer gave me a lot of guidance and suggestions, I have a more personal understanding of senior, but also clear the direction of further study.

The company F

Company Status:

Small and medium-sized cultural and creative companies

Interview:

Interviewer: Do you accept 996?

Me: How much is your recruitment budget?

Results:

This is the shortest interview time I have ever had.

Harvest:

Thank you very much for getting to the point and not wasting your time.

I can work overtime personally, or for free if I’m on a project, but I really don’t want to go to the ICU.

Company G(final entry)

Company Status:

startup

Telephone interview:

The interviewer should be looking at my blog and asking me first about the basics and then about the project. The problem is not a list, with the forefront of most repeat, after all, although the front-end knowledge is more miscellaneous, the main knowledge point can still grasp the context.

A:

The scene side is also not a lot of problems, little sister is very easygoing, didn’t ask too many questions about the technology, because before the phone talked, mainly talk about some is how into the line, work at ordinary times, the problem of solution, what do you do after work at ordinary times, personal development planning, blogging what feeling, learning anything recently, view of overtime… Such as this

2:

The second interview should be with the technical director, and the main questions are about the daily learning (I have mentioned these in my introduction), the daily learning paths, personal development plans and expectations.

Three sides:

The three sides are the CEO and HR of the company. The main questions are about the project, the modules I am responsible for, some questions about project selection, the process of launching some projects, solutions to on-the-job problems, why I want to change jobs, my expectations for the company, and the introduction of some companies.

Results:

I got the offer the next day. I really like the atmosphere of the company. Everyone is easy-going. Looking forward to joining.

Harvest:

I also want to find a front end who can work in the company. I hope to do my job well first, contact more other businesses (such as multi-end, small program, APP, etc.), accumulate precipitation steadily, improve technology, get familiar with business, go deep into the industry, and strive to be a slash youth.

conclusion

The above is the interview process of some summary, there are detailed and slightly, should be some interview I have a recording to do duplicate disc, some inconvenient or forget to record, all rely on memory, some places may be some omission, forgive me.

Come down through these a few interviews, feel this year’s employment pressure is actually quite big. Of course, the gold will always shine, and talent will find a job wherever it is — so come on, guys — don’t be a wimp.

My current rating is around intermediate +. In Shanghai, the salary of a big factory is relatively higher, but the requirements for the foundation and algorithm are also higher. Small companies, the algorithm requirements are not high, browser principles and JS, ES account for a large proportion, the framework is followed, it is best to have some project packaging experience.

Write this blog, mainly is oneself water a blog to do a stage summary, if can help everybody is the best.

advice

Some last words of advice:

  1. Accumulation is very important: we can record some problems encountered in work and their solutions, and make a summary at some time. The best is to find a platform to write blog, Gold, GitHub, blog garden, CSDN can be, a good memory is not as bad as writing, write it yourself is better than read it again. Online blog is not into the convenience of their own access, interview thing encounter not quite remember the knowledge point can also say – I have summarized on the blog.

  2. Don’t put yourself in a hole on your resume: be what you are, and be what you are. Normal interviewers will ask questions based on their resume, so don’t use a noun you don’t understand — just look it up, memorize it, or say one, two, three, even if you don’t understand it. Otherwise, it would be really awkward.

  3. Prepare before an interview: an interview is an exam, and for an exam we have to study. The front-end body of knowledge is pretty clear — pages, styles, JS, frameworks, project packaging and building. Learn what you’re good at, and then eliminate the blind spots.

  4. Don’t fall into the same trap twice: Talk to your interviewer to find out what’s going on. Understand and face your own shortcomings; When you can’t answer some of the interview questions, it’s okay. Go back and look it up. Watch the video. If you forget, you can record it.

  5. Don’t quit naked! Don’t quit naked! Don’t quit naked! : Important things say three times, if there is a mortgage car loan, naked quit looking for a job really great pressure – have food in hand, the heart is not panic. Of course, the tuhao are free…

  6. Try not to drag the time line too long: it is hard to find a job while working, so prepare for the interview after work if you want to ask for leave. So, try to take more than half a month to take a few offers, the time line may be too long slack (I just dragged some long). Try to find the right company (salary, ability, commute, etc.) to interview with. Don’t just show up for an interview when you’re invited, or you’ll be wasting your time.

  7. Correct attitude and keep learning: technology is changing with each passing day and frameworks are emerging one after another. Since you have chosen this industry, you should correct your attitude, study hard, improve your technology, be familiar with the business, go deep into the industry, and don’t let the waves beat you to death.

The appendix

Reference documentation

Intermediate front end of the interview may report | curtilage god king – the nuggets

1. Implementation, advantages and disadvantages of the three-column layout

The layout scheme implementation advantages disadvantages
Float layout Left column left float, right column right float, middle column set left margin It is simpler and more compatible Float elements out of the flow of the document, just be careful to clear float when using them.
The Position layout The left, middle and right columns (in no order) directly set the location of each child element according to the location attribute Fast and easy to set up Elements are removed from the document flow, descendants of elements are removed from the document flow, and when they are highly unknown, they are problematic, less effective and usable
The Table layout Display: table; Child element display: table-cell; Residential elements have no width It is easy to use and compatibility is not a problem ① Cannot set the sidebar margin; ② Not friendly to SEO; ③ When one of the cells is taller than the other, the cells on both sides will also be taller
Flex layout Display: flex; Elements on both sides set width; Home neutron element Flex: 1; More perfect Compatibility problems exist in Internet Explorer, and only Internet Explorer 9 or higher can be supported
The Grid layout Display: grid; Grid implementation Strongest and simplest Compatibility is not good, Internet Explorer 10+ support, and also support only part of the attributes

2. Single line display/three line display

Single line text overflow hidden into…

 p {
    /* Hide the overflow content */
    overflow: hidden;
    /* Single-line display */
    white-space: nowrap;
    /* Overflow displays the ellipsis */
    text-overflow: ellipsis;
  }
Copy the code

Multiple lines of text overflow hidden into…

  p {
    overflow: hidden;
    /* Display the object as an elastic flex box model. * /
    display: -webkit-box;
    /* Limit the number of lines of text displayed in a block element, that is, the line number setting */
    -webkit-line-clamp: 3;
    /* Specifies that the box rows children vertically from top to bottom
    -webkit-box-orient: vertical;
  }
Copy the code

3. Redraw and reflux

Reflux: When part (or all) of a render tree needs to be rebuilt due to changes in the element’s size, layout, hiding, etc. This is called backflow (actually I think it’s easier to call it relayout). Every page needs to be reflow at least once, when the page first loads.

Redraw: When some elements in the Render tree need to update attributes, these attributes only affect the appearance and style of the element, not the layout, such as background-color. It’s called a redraw.

The difference between

  • Backflow inevitably causes redrawing, but redrawing does not necessarily cause backflow. For example, only color changes will result in redrawing and no backflow
  • Backflow is required when the page layout and geometry change

For example: Add or remove visible DOM elements, element position changes, element size changes – margins, fills, borders, width and height, content changes

  • Backflow is often accompanied by changes in layout, which is costly:

  • Redraw only changes the style, the structure does not change:

4. Handwritten Fibonacci sequence and its optimization

Fibonacci sequence (Fibonacci sequence) : The Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, is introduced by the mathematician Leonardoda Fibonacci with rabbit breeding as an example, so it is also called the “rabbit sequence”, refers to the sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34… Mathematically, the Fibonacci sequence is defined recursively as follows: F(0)=1, F(1)=1, F(n)=F(n-1)+F(n-2) (n >2, n∈ n *). The sequence begins with the third term, and each term is equal to the sum of the first two

function Fibonacci (n) {
  if ( n <= 1 ) {return 1};
  return Fibonacci(n - 1) + Fibonacci(n - 2);
}
Copy the code

This method is the least code and easy to understand, but when n is large, it quickly causes stack overflow. The cause is too many “call frames”, which causes browser suspended animation. For more details, see Function extension’s Tail call Optimization – Ruan Yifeng.

  1. Recursion (optimized version)
function Fibonacci2 (n , ac1 = 1 , ac2 = 1) {
  if( n <= 1 ) {return ac2};
  return Fibonacci2 (n - 1, ac2, ac1 + ac2);
}
Copy the code

This method is the optimized writing method of function tail call (ES6 and later versions support the default parameter, ES5 please use the general default value writing method). It is a little complicated to understand, but it does not occur stack overflow. It is recommended to use.

  1. General cycle
function Fibonacci3(n) {
  if (n===1 || n===2) {
        return 1;
    }
    var n1 = 1, n2 = 1, sum;
    for (let i = 2; i < n; i++) {
        sum = n1 + n2
        n1 = n2
        n2 = sum
    }
    return sum
}
Copy the code

The looping version is best understood as giving the initial value and adding it up

  1. Deconstruct the assignment plate
var Fibonacci4 = function (n) {
  if (n===1 || n===2) {
        return 1;
    }
    let n1 = 1; n2 = 1;
    for (let i = 2; i < n; i++) {
        [n1, n2] = [n2, n1 + n2]
    }
    return n2
}
Copy the code

The looping version is best understood as giving an initial value and then adding it up (with deconstructed assignment, the code is simpler).

5. Look at the code output. What are macro tasks and microtasks and what are they?

  setTimeout(function() {
  console.log(1)},0);
new Promise(function executor(resolve) {
  console.log(2);
  for( var i=0 ; i<10000 ; i++ ) {
    i == 9999 && resolve();
  }
  console.log(3);
}).then(function() {
  console.log(4);
});
console.log(5);
Copy the code

Output:

2, 3, 5, 4, 1Copy the code

Macro task

# The browser Node
setTimeout Square root Square root
setInterval Square root Square root
setImmediate x Square root
requestAnimationFrame Square root x

Micro tasks

# The browser Node
process.nextTick x Square root
MutationObserver Square root x
Promise.then catchfinally Async/Await Square root Square root

Enforcement mechanism:

  1. Execute the main thread first
  2. When you encounter a macroTask, put it on a macroTask queue.
  3. Encounter a microtask and put it in a microtask
  4. The main thread is finished
  5. The microtask is executed. Procedure
  6. Execute a task in the macroTask queue once, and the execution is complete
  7. The microtask is executed
  8. Cycle…

6. Write javascript deepClone function

/ / copy
/** * Deep copy object, can serialize the date correctly *@param {*} obj* /
export const DEEP_CLONE = function (obj) {
  let objClone = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        // Check whether the ojb child is an object, if so, copy recursively
        if (obj[key] && typeof obj[key] === 'object') {
          // Deep copy date type
          if (obj[key] instanceof Date) {
            objClone[key] = new Date(obj[key].valueOf())
            // console.log('deepClone', objClone[key])
          } else {
            objClone[key] = DEEP_CLONE(obj[key])
          }
        } else {
          // If not, simply copy
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}

Copy the code

7. Two modes of Vue routing

hash

The principle of

  • Early implementations of front-end routing were based on location.hash, where the value was the URL following the #

The idea is to listen after # to make Ajax requests for local updates without refreshing the entire page.

  • Use hashChange events to listen for URL changes. When a URL changes, the browser moves forward and backward, the A tag changes the URL, or the window. Location changes the URL.

advantages

Compatible with earlier browsers, Angular1.x and Vue use hash routing by default

Only the hash before the # symbol is included in the request and sent to the back end, which means that even if the back end does not fully cover the route, it will not return the 404 error hash value change, which will add a record to the browser’s access history. So the ability to toggle the hashes controlled by the browser’s back and forward buttons overtakes the anchor positioning element

disadvantages

Not very beautiful, # after the transmission of complex data will cause problems

history

The principle of

  • History provides pushState and replaceState methods to record the state of the route. These methods change the URL without causing the page to refresh
  • History provides popState events that are similar to hashChange events, but popState events are a little different: Popstate events are triggered when the URL is changed backwards and forwards by the browser, but not when the URL is changed by pushState/replaceState or the A tag. The good news is that we can detect URL changes by intercepting pushState/replaceState calls and a tag click events, so listening for URL changes is possible, but not as convenient as hashchange.
  • Both pushState(state, title, URL) and replaceState(state, title, URL) can take the same three parameters.

advantages

Simple to use, more beautiful

PushState () sets the new URL to be any URL that has the same origin as the current URL, while the hash can only change the contents after the #, so only the same document as the current URL can be set

PushState () is also added to the history stack if the URL is exactly the same as the current URL, and the contents after the hash# must be modified to be added to the new stack

PushState () can add any type of data to the record with the stateObject parameter, while hashes can only add a short string pushState(), which can also set the title attribute for later use

disadvantages

The URL on the front end must be the same as the URL on the back end of sending the request. Otherwise, a 404 error will be reported

Due to the History API, older browsers have row compatibility issues

Two different use scenarios

  • As you can see from the previous section, hash urls have # tags. You can use history mode when you want a more elegant URL.
  • When using the History pattern, it is important to add a candidate resource on the server that covers all cases: if the URL does not match any static resources, it should return the same index.html page that your app depends on.
  • To be compatible with browsers of earlier versions, you are advised to use the hash mode.
  • When you need to add any type of data to a record, you can use the History mode.

8. Write a JS event binding function

  const Event = {
    on() {} / / binding
    off() {} / / unbundling
    trigger() {} // Triggers the event
};
Copy the code
class Event {
  constructor() {
    // Use objects quickly for lookup
    this._cache = {};
  }
  // Bind the event
  on(eventName, callback) {
    /* For convenience and space saving, put the same type of events in an array. * Since arrays are ordered, they are logically queued
    // Add a new function if there is one, and add a new function if there is no one
    let fns = (this._cache[eventName] = this._cache[eventName] || []);
    // If the event method does not exist, put it in the dictionary
    if (fns.indexOf(callback === -1)) {
      fns.push(callback);
    }
    return this;
  }
  // Triggers the event
  trigger(eventName, data) {
    // Check the dictionary for the function name, and if so, trigger it
    let fns = this._cache[eventName];
    if (Array.isArray(fns)) {
      // If any, pass data to each of the opposite functions
      fns.forEach(fn= > {
        fn(data);
      });
    }
    return this;
  }
  /* Unbind the name of the event from the dictionary
  off(eventName, callback) {
    let fns = this._cache[eventName];
    if (Array.isArray(fns)) {
      if (callback) {
        let index = fns.indexOf(callback);
        if(index ! = = -1) {
          fns.splice(index, 1); }}else {
        // Empty all
        fns.length = 0; }}return this; }}const event = new Event();
event.on("test".a= > {
  console.log(a);
});
event.trigger("thet"."hello world"); // Output after binding

event.off("test");
event.trigger("test"."hello world"); // It will not be displayed after unbinding

Copy the code

9. Write the deduplicate function

  const arr = [1.'1'.'1'.'NaN'.NaN.'NaN', {a: 1}, '{a: 1}', {a: 1}]

Copy the code
// Use for to nest for, then splice to deduplicate (ES5 most common)
function unique2(arr) {
   for (var i = 0; i < arr.length; i++) {
     for (var j = i + 1; j < arr.length; j++) {
       if (arr[i] == arr[j]) {         // The first is equal to the second, and the splice method removes the second
         arr.splice(j, 1); j--; }}}return arr;
 }

  / / by using hasOwnProperty
  function unique7(arr) {
   var obj = {};
   return arr.filter(function (item, index, arr) {
     return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})}/ / use the filter
function unique4(arr) {
   return arr.filter(function (item, index, arr) {
     // The current element, the first index in the original array == the current index value, otherwise return the current element
     return arr.indexOf(item, 0) === index;
   });
 }
Copy the code

Mixin/custom instruction/V-if/V-SSD/diff algorithm

11 handwritten ajax

/ / handwritten ajax
function get(){  
  var req = new XMLHTTPRequest();  
  if(req){  
      req.open("GET"."Http://test.com/?keywords= mobile phone".true);  
      req.onreadystatechange = function(){  
          if(req.readyState == 4) {if(req.status == 200){  
                  alert("success");  
              }else{  
                  alert("error"); } } } req.send(); }}Copy the code

12 Event binding function + event delegate

function delegate(element, eeventType, selector, fn) {
  element.addEventListener(eventType, e= > {
    let el = e.target
  })
}

Copy the code

13 Promise instance

// Promise
function fn(){ 
  var promise = new Promise(function(resolve,reject){
    // ... some code
    if(/* Asynchronous operation succeeded */) {
    resolve(value) // The successful call to resolve passes arguments down and accepts only one argument
    }else {
    reject(error)  // Fail to call Reject, passing arguments down and accepting only one argument}});return promise
}

fn.then(function (r) {
  console.log('Success:' + r);
}).catch(function (reason) {
  console.log('Failure:' + reason);
});
// All calls were successful
Promise.all([promise1,promise2]).then(sucess1,fail1)
// Call when there is a success
Promise.race([promise1,promise2]).then(sucess1,fail1)
Copy the code

Make your own promises

  • You must write promises by hand
class MyPromise{
    constructor(executor) {
        this.status = "pending";     // Initialize the state to pending
        this.value = undefined;      // Initialize the returned result of success or the cause of failure
        
        // This is the resolve method, which changes the state to resolved and returns the result
        let resolve = result= > {
            if(this.status ! = ="pending") return;  // Once the state changes, it will not change again
            this.status = "resolved";
            this.value = result;
        }
        
        / / here is a method that reject exception, status is changed to the rejected, and the cause of the failure to return
        let reject = reason= > {
            if(this.status ! = ="pending") return;
            this.status = "rejected";
            this.value = reason;
        }
        // The try and catch methods catch the exception. If an error occurs, the reject method is executed
        try {
            executor(resolve, reject)
        } catch(err) {
            reject(err)
        }
    }
}

Copy the code

Principle and use of VueX

  • Rationale and use of Vuex

  • A simple understanding of how Vuex works

16 Vue Permission Routing implementation mode

Summary of Vue permission routing implementation

17 js judge objects and arrays

Determine an object or array

18 What does new() do in js?

  • What does new() do in js? (https://www.jianshu.com/p/bf4cda6b515f)

19 the sorting

  • Eight basic sorting summary

  • Summary of top 10 classic sorting algorithms (described in JavaScript)

  • Basic sorting algorithm

The advanced

  • Elegant JavaScript sorting algorithm (ES6)

20 Vue Route transmission parameter ——– The difference between params and query

Background: In the project, values need to be passed across pages, such as the test id, and the values will disappear after the refresh, so the differences between the two are studied

  1. Params can only import routes using name, query can import routes using path
  2. Params is similar to post, and Query is much more similar to the get parameter we use in Ajax. To make it simpler, the former does not display the parameter in the browser address bar, while the latter does, so params is safer to pass values.
  3. The values are similar to this.route.params.name and this.route.params.name and this.route.params.name and this.route.query.name.
  4. The params pass is gone when refreshed, but the Query pass is still there
this.$router.push({
path:"/detail".params: {name:'nameValue'.code:10011}});this.$router.push({
path:'/xxx'
query: {id:id
}
})
Copy the code

Summary: Use this method for a small number of parameters, and if there is a large amount of public data, use Vuex or local storage.

Postscript: Hello friends, if you think this article is good, remember to click a “like” or “star”, your “like” and “star” are the motivation for me to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial – Share in the same way 4.0 International licenseLicense.

Based on thegithub.com/danygitgitOn the creation of works.

Permissions outside of this license agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.