1. How to realize asynchronous programming?

Asynchronous programming implementations can be divided into the following categories:

  1. Callback function form: Asynchronous programming is implemented through callback functions, so that different tasks are executed in sequence, and the next one will be executed only after the previous one is completed. However, the disadvantage is that when the number of tasks is large, layers of nested callback hell will occur, resulting in complex code redundancy and difficult to maintain.
  2. Promise object: Promise can solve the callback hell problem by creating a Promise instance object using new and accepting a callback function as an argument. The function accepts two state functions, resolve and Reject, indicating that the state changes from the wait state to the successful and failed state. The returned Promise object can be chain-called through.then to implement the sequential function operation.
  3. The function of generator+yield, * has the next function, that is, the function returns an object. Each call to the next function continues execution of the suspended code. The following is a simple implementation of a Generator function that transfers execution away during the execution of a function and back outside the function. We transfer execution out when we encounter an asynchronous function and back when the asynchronous function is finished executing. This allows us to write asynchronous statements synchronously inside functions.
  4. Async and await: An ordinary function is preceded by async to transform the function into an asynchronous function that returns a promise object. When an await statement is executed inside the function, if the statement returns a promise object, the execution will proceed after the current statement is completed. Try -catch errors when encountered;

2. Synchronous and asynchronous?

Synchronization means that when a client sends a request to a server, the client does nothing else while waiting for the server to respond to the request. Return to the client when the server is done. So the client has to wait. User friendly. — Synchronization is to execute tasks in sequence, the following code will not execute until this code is finished;

Asynchrony means that when a client sends a request to a server, the client can do other things while waiting for the server to respond, which saves time and improves efficiency.

— Extension: Promise and async functions optimize operations performed by asynchronous tasks; The following code is executed before the asynchronous task is finished, so what if you need some of the results of the asynchronous task for subsequent operations? Then there are solutions like Promise and Async.

3. Understand async/await and its advantages over Generator

Async await is used to solve asynchrony. Async is the syntactic sugar of Generator functions. Async replaces the asterisk (*) of Generator functions with async and yields with await.

Async is represented with the keyword async and await is used inside the function

The async function returns a Promise object, and callbacks can be added using the then method

When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body

Advantages of Async over Generator:

(1) Built-in actuators. The co module is created because the execution of Generator functions depends on the executor. Aysnc functions have their own executor and are called in the same way as ordinary functions. The execution of async functions requires only one line.

(2) Better semantics. Async and await are more semantic than * and yield; Async means that there is an asynchronous operation inside a function, and await means that the following expression needs to wait for the result;

(3) wider applicability. According to the convention of the CO module, yield can only be followed by Thunk or Promise objects, and async can be followed by Promise or primitive type values

(4) Return the Promise. Async functions return Promise objects, which are more convenient than iterators returned by Generator functions and can be called directly using then()

If the Promise object after await becomes reject, the reject argument is received by the catch callback.

async function f() {
  await Promise.reject('Wrong'); } f (). Then (v = > console. The log (v)). The catch (e = > console. The log (e)) / / wrongCopy the code

Notice that the await statement is preceded by no return, but the reject argument is still passed to the catch callback. Here the effect is the same if return is preceded by await.

Any Promise object after an await statement becomes reject, and the entire async function breaks.

async function f() {
  await Promise.reject('Wrong');
  await Promise.resolve('hello world'); // do not execute}Copy the code

In the above code, the second await statement will not be executed because the state of the first await statement changes to reject.

Sometimes we want to not interrupt subsequent asynchronous operations even if the previous one fails. We can then put the first await in a try… Inside the catch structure, so that the second await is executed regardless of whether the asynchronous operation succeeds or not.

async function f() {
  try {
    await Promise.reject('Wrong');
  } catch(e) {
  }
  return await Promise.resolve('hello world');
}

f()
.then(v => console.log(v))
// hello world
Copy the code

The alternative is to await a Promise object followed by a catch method to handle any errors that may occur earlier.

async function f() {
  await Promise.reject('Wrong')
    .catch(e => console.log(e));
  return await Promise.resolve('hello world'); } f().then(v => console.log(v)Copy the code

Above is an introduction to using async await.

4. What are Promise objects

1. Promise:

Promise objects are a solution to asynchronous programming. Promise is a constructor that creates a Promise instance object, accepts a callback function as an argument, and returns a Promise instance with three states: Pending, Resolved and Rejected. The status can only be changed from “Resolved” to “Volatile” or “Rejected”. After the status changes, it will not change to any other state. Switch the state after the asynchronous task by calling the Resolved or Rejected methods, return a Promise object, and define the Resolved and Rejected callback functions through a. Then chain call.

In JS, ajax is often used asynchronously, such as sucess: one callback, error: one callback. But if callback hell is created when multiple interfaces are required for a single request, promises can be handled with then, which can write a promise object inside a THEN; The then method handler is executed on success, and the error handler in catch is executed on failure.

Promise itself has race, All, Reject, and resolve, while the prototype has then and catch methods.

Promise.prototype.then()

Then adds a callback function to the Promise instance when the state changes. The first argument to the THEN method is the resolved state callback, and the second argument (optional) is the Rejected state callback.

The then method returns a new Promise instance (note, not the original Promise instance). So you can write it chained, where a then method is followed by another THEN method.

Promise.prototype.catch()

The promise.prototype.catch () method is an alias for. Then (null, Rejection) or. Then (undefined, Rejection) that specifies the callback when an error occurs

Method returns a Promise object and if the state becomes Resolved, the callback specified by the then() method will be called; If an asynchronous operation throws an error, the status changes to Rejected, and the callback specified by the catch() method is called to handle the error. In addition, callbacks specified by the then() method are also caught by the catch() method if an error is thrown during execution.

promise.all

Promise.all can wrap multiple Promise instances into a new Promise instance. Also, success and failure return different values, with success returning an array of results and failure returning the first rejected state.

promise.race

Race ([P1, P2, p3]) returns the result of the first completed task. Promise.race([P1, P2, p3]) returns the fastest result, regardless of whether the result itself is a success state or a failure state.

Disadvantages of Promises:

  1. You can’t cancel a promise. Once you create a promise, it executes immediately.
  2. If the callback function is not set, the Promise will throw an error internally and not externally
  3. When in a pending state, you do not know what stage of progress is being made.

What is the difference between a reject and catch in a Promise

Reject is used to throw exceptions and catch is used to handle exceptions

Reject is a method for a Promise, and catch is a method for an instance of a Promise

Anything after reject must go into the second callback in THEN, or catch if no second callback is written in THEN

Network exceptions (such as disconnection) go directly to catch and not to the second callback of THEN

Promise has several states. When does it go into a catch?

Three states:

Pending, depressing, reject

Two processes:

Padding-> pity, PADDing-> Rejected When pending is rejectd, the catch will be entered

5. What is the output of the following

const promise = new Promise((resolve, reject) => {

console.log(1);

resolve();

console.log(2);

})

promise.then(() => {

console.log(3);

})

console.log(4);

A Promise executes immediately after it is created, so it prints 1,2 first, while the code inside promise.then () executes immediately at the end of the next event loop, so it continues to print 4, and finally prints 3

6. What is the difference between ES5 and ES6? Tell me about ES6

In ES5, there is no block-level scope, and var has variable promotion. In let, variables used must be declared

2) Arrow function ES6 no longer uses the keyword function(), but uses ()=> instead

3) Template strings Template strings are enhanced strings, identified by backquotes (‘), that can be used either as regular strings or to define multi-line strings

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern

5) For the cycle of… The of loop can iterate over groups of numbers, Set and Map structures, some array-like objects, objects, and strings

ES6 standard, Js native support module (module). The JS code is divided into small blocks of different functions for modularization, the code of different functions are written in different files, each module only needs to export the public interface part, and then through the import of the module can be used in other places

A set data structure is similar to an array. All data are unique and have no duplicate values. It is itself a constructor

8)… The expansion operator converts the values of an array or object into a comma-separated list of arguments. The expand operator allows you to expand an array without using the Apply method, convert an array to a parameter of a function, and collect multiple values into a single variable

// ES5functionf(x, y, z) { // ... } var args = [0, 1, 2]; f.apply(null, args); // ES6function f(x, y, z) {
  // ...
}
letargs = [0, 1, 2]; f(... args); Here is a practical example of the extension operator replacing apply to simplify writing the largest element of an array using math.max. Math.max. Apply (null, [14, 3, 77]) math.max (... [14, 3, 77]) // equivalent to math.max (14, 3, 77);Copy the code

Expansion operators can be used to copy arrays; Merge arrays (both shallow copies); Combined with deconstruction assignment to generate arrays; Turn a string into a real array; The array. from method is used to convert two types of objects into true arrays: array-like objects and iterable objects (including the new ES6 data structures Set and Map).

With async/await and promise, you can write code that looks like synchronization to handle asynchronous processes and improve the code’s conciseness and readability. Async is used to declare that a function is asynchronous. Await is used to wait for an asynchronous method to complete

12) Promise is a solution to asynchronous programming that is more reasonable and powerful than traditional solutions (callback functions and events)

7. Var, let, const

  • Var declarations can be repeated, while let declarations cannot be repeated
  • Var is not limited to the block level, while LET is limited to the block level
  • Var maps to Window (hanging an attribute), while let does not map to Window
  • Var can access a variable above a declaration, while let has a temporary dead band. Accessing a variable above a declaration will result in an error
  • Const must be assigned after the declaration or an error will be reported
  • Const defines an immutable quantity, and an error is reported if it changes
  • Const, like let, does not map to window, supports block-level scope, and raises an error when accessing a variable above a declaration

What’s important about let and const?

  1. Variables declared by lets and const cannot be promoted.
  2. Let and const have their own separate scope.
  3. Duplicate declarations are not allowed. Duplicate declarations will cause an error.
  4. A variable declared by const is not allowed to change its value. Const is a constant. If the value of const is changed after an object, the value of const is changed without error.


8. Arrow function

A few things to note when using the arrow function:

{} and return can be omitted when there is only one statement; Multiple statements cannot be omitted;

When {} and return are omitted, if the return is an object, the object uses () parentheses;

/ / an errorlet getTempItem = id => { id: id, name: "Temp"}; / / is not an errorlet getTempItem = id => ({ id: id, name: "Temp" });Copy the code

(1) If the arrow function is used, this does not refer to the window, but to its parent. (2) If the arrow function does not have its own this, call, apply, and bind are invalid.)

In the arrow function, the reference to this is fixed; This always refers to the object where the function definition takes effect

(2) You can’t use arguments. This object does not exist in the function body. If you do, use the REST argument instead.

Arguments. length is the number of arguments to the function. Arguments. callee refers to the function itself. So, in order to use an Array, the method of Array must be used. The prototype. Slice. Call, to convert the Array; Rest arguments do not have this problem, they are a real array, array specific methods can be used - (ES6 new REST arguments:) REST arguments: form (... Arguments), which gets extra arguments to a function so you don't need to use arguments objects; The rest argument's variable is an array that puts the extra arguments into the array;Copy the code

How can an array-like object be converted into an array object?

1. Array. The from () method (2) array. The prototype. Slice. The call (elems) method into the array; 3.[... elems] (expansion operator) method to array; 4. Array. Prototype. ForEach. Call (elem, callback) methodCopy the code

(3) Cannot be used as a constructor, which means that the new command cannot be used, otherwise an error will be thrown

What does the new operator do? // (1) create a new empty object // (2) set the prototype of the object to the function's prototype object. // (3) add attributes and methods to the object referenced by this, and implicitly return this;Copy the code

(4) Yield cannot be used, so arrow functions cannot be used as Generator functions

Arrow functions can’t be used in constructors, have no prototype property, can’t bind arguments objects, and can’t use call and apply.


9.Symbol type of attention points and Symbol value mandatory class conversion?

ES6 allows explicit casts from symbols to strings, however implicit casts produce errors. Symbol values cannot be cast to numbers (both explicit and implicit yield an error), but can be cast to booleans (both explicit and implicit result)true).Copy the code

Values of type Symbol cannot be converted to numbers and an error is reportedCopy the code

Symbol type:

  • 1. Do not use the new command before the Symbol function, otherwise an error will be reported.
  • 2. The Symbol function can accept a string as an argument representing a description of the Symbol instance, mainly for display on the console or for easy differentiation when converted to a string.
  • 3.Symbol is the attribute name. This attribute does not appear in for… In, for… Of loop, will not be the Object. The keys (), Object, getOwnPropertyNames (), JSON. The stringify () returns.
  • 4. Object. GetOwnPropertySymbols method returns an array of all members is the current Object is used as the Symbol value of the property name.
  • 5.Symbol.for takes a string as an argument and searches for a Symbol value named with that argument. If so, return the Symbol, otherwise create and return a Symbol with the name of the string.

Symbol. For () and Symbol() both generate a new Symbol. The difference is that the former will be registered in the global environment for search, while the latter will not. Symbol.for() does not return a new Symbol value each time it is called. Instead, it checks to see if the given key already exists and creates a new value if it does not. For example, if you call symbol.for ("cat"30 times, each time returns the same Symbol value, but the call to Symbol("cat")30 times, 30 different symbols are returned. Symbol.for("bar") === Symbol.for("bar") / /true

Symbol("bar") === Symbol("bar") / /falseIn the code above, since the Symbol() notation has no registration mechanism, each call returns a different valueCopy the code

  • The Symbol. KeyFor method returns the key of a registered Symbol type value.

let s1 = Symbol.for("foo");
Symbol.keyFor(s1) // "foo"

let s2 = Symbol("foo");
Symbol.keyFor(s2) // undefinedCopy the code

10. What are the new features of ES6 template strings? And implement a class template string function

Basic string formatting.

Concatenate an expression into a string.

In ES5 we use a backslash () to do multi-line strings or string concatenation.

ES6 backquotes (‘ ‘) solve the function of class template strings

let name = ‘web’; let age = 10; Let STR = ‘hello ${name} is ${age} years old’ STR = STR. Replace (/ $\ \ {\} ([^}] *)/g, function () {return eval (the arguments [1]). }) console.log(str); // Hello, Web is 10 years old

11. Introduce the difference between Set, Map, WeakSet and WeakMap?

Application scenario Set is used for data reorganization, Map is used for data storage,

Set:

The set itself is a constructor that generates the set data structure; When you add a value to a Set, no type conversion occurs, so 5 and “5” are two different values.

The object.is () method is used inside a Set to determine whether two items are equal. The only difference is that +0 and -0 are considered equal in a Set.

// Remove duplicate members from array [...new Set(array)]Copy the code

The array. from method converts a Set structure to an Array. This provides another way to remove duplicate members of an array.

function dedupe(array) {
  return Array.from(new Set(array));
}

dedupe([1, 1, 2, 3]) // [1, 2, 3]Copy the code

The above method can also be used to remove duplicate characters from a string.

[...new Set('ababbc')].join(' ') / /"abc"Copy the code
  • Set.prototype.add(value): adds a value and returns the Set structure itself.
  • Set.prototype.delete(value): Deletes a value and returns a Boolean value indicating whether the deletion was successful.
  • Set.prototype.has(value): Returns a Boolean value indicating whether the value isSetA member of.
  • Set.prototype.clear(): Clears all members with no return value.

If you want to change the Set structure synchronously during traversal, there is no direct way, but there are two workarounds. One is to use the original Set structure to map a new structure, and then assign a value to the original Set structure; The other is to use the array. from method.

/ / methodlet set = new Set([1, 2, 3]);
set = new Set([...set].map(val => val * 2));
// setIs 2, 4, 6 // Method twolet set = new Set([1, 2, 3]);
set = new Set(Array.from(set, val => val * 2));
// setThe values of theta are 2, 4, 6Copy the code

(1) Members cannot repeat

(2) Only key values without key names, similar to an array

(3) Can traverse, methods include add, delete,has

Map:

(1) Two instances of the same value are treated as two keys in the Map structure;

(2) Is essentially a collection of key-value pairs, similar to a collection, but the scope of “key” is not limited to strings, all types of values (including objects) can be used as keys

(3) It can be traversed and converted with various data formats

(4) Use the set() method to add key-value pairs to Map; The get() method extracts values from the Map; The has(),delete(), and clear() methods


Set and WeakSet structure?

  • 1.ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
  • 2.WeakSet structure is similar to Set, which is also a collection of non-repeating values. WeakSet is a constructor that you can usenewCommand to create WeakSet data structure. butWeakSet members can only be objectsCannot be any other type of value. WeakSet objects are Weak references, may disappear at any time, traversal mechanism cannot guarantee the existence of members, that is, garbage collection mechanism does not consider WeakSet reference to the object, that is, when there is no reference outside Weak Map, the key value pair will be removed;
  • Weak Set does not have forEach() and cannot be iterated. Weak Set cannot be used for for-of loops.
  • Weak Set does not have size;

WeakSet can only place objects.

Secondly, the objects in WeakSet are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is to say, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet.

This is because the garbage collection mechanism relies on reference counting and does not free the memory if the number of references to a value is not zero. After you finish using the value, you sometimes forget to dereference it, causing memory to be unable to be freed, which can lead to a memory leak. WeakSet references are not included in the garbage collection mechanism, so there is no problem. Therefore, WeakSet is suitable for temporarily storing a group of objects and information bound to the object. As soon as the object disappears externally, its reference in WeakSet disappears automatically.

Due to the above feature, a WeakSet member is not suitable for reference because it will disappear at any time. In addition, because the number of internal WeakSet members depends on whether the garbage collection mechanism is running, the number of members may be different before and after the operation, and when the garbage collection mechanism is running is unpredictable, so ES6 stipulates that WeakSet cannot be traversed.

Map and WeakMap?

  • 1.Map data structure. It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as keys.
  • 2.WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs. However, WeakMap only accepts objects as key names (except null), and does not accept other types of values as key names. Using non-object keys will throw errors, and these objects are weak references and do not interfere with garbage collection. If the key in the Weak Map is not referenced outside the Weak Map, the key-value pair is removed.

12. What is a tail call and what are the benefits of using it?

A tail-call is when the last step of a function calls another function. Our code execution is stack based, so when we call another function in one function, we keep the current execution context and then add another execution context to the stack. With tail-call optimization, we can save memory by not having to keep the current execution context because it is already the last step of the function. But ES6 tail-call optimization is only enabled in strict mode, not normal mode.

13. How to say class in ECMAScript 6?

Introduction of class:

Js there is no obvious Class object-oriented method, so ES6 introduced Class (the concept of Class), through the Class keyword can define the Class;

Es5:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ') ';
};

var p = new Point(1, 2);Copy the code

ES6 class is a syntactic candy that does most of what ES5 does. The new class writing method just makes object prototype writing clearer and more like object-oriented programming syntax

Class Point {constructor(x,y) {this.x = x; //this keyword represents the instance object this.y = y; }toString() {
       return '(' + this.x + ', ' + this.y + ') '; 
  }
}
var p = new Point(1, 2);Copy the code

Constructor () {constructor (); / / class (); / / class (); / / class (); / / class (); All methods of a class are defined on the prototype property of the class;

Note:

(1) Strict mode

Inside classes and modules, the default is strict mode, so there is no need to use strict to specify the runtime mode. As long as your code is written in a class or module, only strict mode is available. Considering that all future code will actually run in modules, ES6 actually upgrades the entire language to strict mode.

(2) There is no promotion

Unlike ES5, there is no hoist for the class.

(3) The direction of this

Class methods that contain this inside point to instances of the class by default.

Differences between ES6 and ES5 inheritance:

Es6: Class can be inherited using the extends keyword. You can only use this keyword in the constructor of a subclass after calling super, otherwise an error will be reported. This is because subclass instances are built based on processing superclass instances, and only super methods can return superclass instances.

Class Point{constructor(x,y){this.x=x; this.y= y; } } class ColorPoint extends Point{ constructor(x,y,color){ super(x,y); // Call the parent class constructor (x, y) this.color = color; }toString() {return this.color + ' '+ super.toString(); // Call the parent toString; }}Copy the code

Inheritance in ES5 is implemented through the Prototype or constructor mechanism. You essentially create an instance object of the subclass and then add the Parent class’s methods to this (parent.apply (this)).

In ES5, each object has a __proto__ attribute that points to the corresponding constructor’s Prototype attribute Class as the syntax sugar of the constructor, as well as the Prototype attribute and __proto__ attribute, so there are two inheritance chains at the same time.

  1. The __proto__ attribute of a subclass, indicating constructor inheritance, always points to the parent class;
  2. The prototype attribute’s __proto__ attribute, which indicates method inheritance, always points to the prototype attribute of the parent class;

ES6’s inheritance mechanism essentially creates an instance object of the superclass, this(so you must call the super() method of the superclass first, and then modify this with the constructor of the subclass. ES6 defines classes using the class keyword, which contains constructors, and extends classes through the extends keyword. Subclasses must call the super method from the constructor method, otherwise new instances report an error. Because subclasses don’t have their own this object, they inherit this from their parent class and then call it. If you don’t call super, subclasses don’t get this.

Note: the super keyword refers to an instance of the superclass, which is the this object of the superclass. In the subclass constructor, the this keyword can only be used after super is called, otherwise an error is reported.

Please refer to es6.ruanyifeng.com/#docs/class


14. Differences between setTimeout, Promise, Async/Await

The event loop is divided into macro task queue and micro task queue

The setTimeout callback is placed in the macro task queue until the execution stack is empty

The callback function in promise.then will be placed in the microtask queue of the corresponding macro task until the synchronous code in the macro task completes execution

Async means that there may be an asynchronous method inside the function, await followed by an expression

When an async method executes, an await expression is immediately executed and the code following the expression is placed on the microtask queue, freeing the execution stack for the synchronous code to execute first


15. Design an object whose key name contains at least one symbol type and iterate over all keys

let name = Symbol(‘name’); Let product = {[name]:” “, “price”:799}; Reflect.ownKeys(product);

16. Following the Set structure, what is the printed size value

let s = newSet(); s.add([1]); s.add([1]); console.log(s.size);

Answer: 2

The two arrays [1] do not have the same value, and the arrays they define correspond to different storage addresses in memory, so not the same value can be stored in the Set structure, so the size is 2

17. Write a promise using class

Class Promise{constructor(executer){constructor(){this.status = ‘pending’; Value = undefined// Default value for success undefined this.reason = undefined// Default value for failure undefined// State can only be changed pending If (this.status == pending){this.status = ‘resolve’; this.value = value; Let rejectFn = reason =>{if(this.status == pending){this.status = ‘reject’; this.reason = reason; } // pass resolve and reject to executer executer(resolve,reject); }catch(e){ reject(e); OnFufilled if(this.status = ‘resolve’){onFufilled(this.value); } // Call onReject if(this.status = ‘reject’){onReject(this.reason); }}}

18. How do I use Set to remove weights

Let arr =,43,23,43,68,12 [12]; let item = […new Set(arr)]; console.log(item); / / [12, 43, 23, 68]

Var array = array. from (new Set (array));

17. Change the form for loop below to for of

Let arr =,22,33,44,55 [11]; let sum = 0; for(let i=0; i

The answer:

Let arr =,22,33,44,55 [11]; let sum = 0; for(value of arr){ sum += value; }

19. Talk about the import/export module of ES6

Import through the import keyword

// Import only one import {sum} from “./example.js” // Import multiple import {sum,multiply,time} from “./exportExample.js” // Import a whole module import * as example from “./exportExample.js”

Export using the export keyword

Var firstName = ‘Michael’; var firstName = ‘Michael’; export var lastName = ‘Jackson’; export var year = 1958; Var firstName = ‘Michael’; var firstName = ‘Michael’; var lastName = ‘Jackson’; var year = 1958; export {firstName, lastName, year}; Let bosh = function CRS (){} export default bosh; import crc from ‘crc’; // If export default is not used, the corresponding import statement needs braces. Let bosh = function CRS (){} export bosh; import {crc} from ‘crc’;


Reference: recommend ruan Yifeng ES6 tutorial: es6.ruanyifeng.com/#docs/funct…

www.jianshu.com/p/bf7565548…