Variable correlation (let, var, const, function)

  • Let and const can both be declaredBlock-level scopeThe usage of LET is similar to var. Let does not promote variables, but is locked in the current block.
  • Const is a constant, guaranteedThe pointer is fixed;Declare and assign

Let, const, var

1. Duplicate declaration – var allows duplicate declaration, let and const do not

2. Variable promotion — declare and define all keywords with var and function in the current scope in advance [pre-parsing]

  • Var raises the declaration of variables to the top of the current scope; There is no variable promotion for let, const.

3. Block level scope

Var has no block-level scope. Let /const has block-level scope. Declaring a variable with let/const inside a separate {} (without function curly braces) creates a block-level scope that is inaccessible to outsiders.

4. Temporary dead zones

  • Variables or constants declared by let and const are automatically “bound” to the scope as long as they exist in the scope. They are no longer affected by the external scope. Let and const have a temporary dead band
var name='jack';
{
 name='bob';
 let name;    //Uncaught ReferenceError: Cannot access 'name' before initialization
}
Copy the code

5. Window object properties and methods:

In global scope, variables declared by var and functions declared by function automatically become properties or methods of the window object. Let and const do not.

2. Template string

  • Template strings are represented by backquotes, and can be used directly within the string, as well as through variables and expressionsThe ${}injection
  • In a template string, all whitespace, line feeds, or indentation are preserved in the output

Arrow function

1. Structure of arrow function

      const/letFunction name = Parameter => Function bodyconst add = () = > {};
Copy the code

2. Arrow function simplification —- Single arguments can omit parentheses, single line function body can omit curly braces and return

3. This point

1.Global scopedthisPoint to theconsole.log(this); // window

2.In general functions (non-arrow functions)thisPoint to the// 'use strict';
      function add() {
        console.log(this); 
        // Strict mode refers to undefined
        // undefined->window
      }
      add();
     
     
3.Click eventthisPoint to thedocument.onclick = function () {
         console.log(this);  / / this point to the document
       };
   
      // This refers to only when the function is called
      // This does not matter where the function is called, but who is calling it
      // In the absence of a specific object, this refers to undefined and, in non-strict mode, to Window
      
4.In the arrow functionthisThe pointing arrow function does not have its ownthis", so it looks out from the upper context layer by layerthisAnd finally foundwindow, histhisPoint to thewindow
Copy the code

4. Scenarios where arrow functions are not applicable

  • 1. Arrow functions cannot be constructors
  • 2. Do not use arrow functions when you want this to point to the calling object
      document.onclick = function () {
        console.log(this);
      };
      document.addEventListener(
        'click'.() = > {
          console.log(this); //window
        },
        false
      );
    Copy the code
  • 3. Do not use arrow functions when you need arguments

4. Deconstruct assignment

Deconstructing assignment means parsing the structure of a piece of data, extracting what we want and assigning values to variables or constants;

4.1 Array Deconstruction assignment (Index equality and pattern Matching)

Array deconstruction assignment is very simple, follow the pattern matching principle and index value of the same assignment can be done, if the structure does not need to skip with a comma.

4.1.1 Default Values, not deconstructed, use default values (lazy evaluation)

The default value is valid only if an array member is exactly equal to (===) undefined

[a = 1, b = 2] = [3.undefined];
//a=3,b=2
Copy the code

4.1.2 Application of array deconstruction assignment

  • 1. Common destruct assignment of class arrays

  • 2. Deconstructive assignment of function parameters

  • 3. Swap variable values

4.2 Object Deconstruction assignment (pattern matching and attribute name identical)

// Complete assignment with the same attribute name, alias can be taken
      const { age, username: uname } = { username: 'Alex'.age: 18 };
      console.log(age, uname);// Uname is assigned after destructing the assignment
Copy the code
  • The default values are the same as for arrays

  • If a declared variable is used for a destructuring assignment of an object, the entire assignment is done in parentheses to prevent it from being treated as a block-level scope

     let x = 2;
    ({ x } = { x: 1 });
    console.log(x);    / / 1
    Copy the code

Application of object deconstruction assignment

  • 1. Deconstructive assignment of function parameters
     const PersonInfo = (user) = > console.log(user.username, user.age);
     PersonInfo(({ age, username: username } = { username: "alex".age: 18 })); // Alex 18 uses a deconstructed value
     
     const person = ({ age = 0, username = "ZhangSan" }) = >console.log(username, age);
     person({}); //ZhangSan 0 uses the default value
     person({ username: "alex".age: 18 }); // Alex 18 uses a deconstructed value
Copy the code
  • 2. Complex nesting

4.3 Deconstruction and assignment of strings

  • Strings can be destructively assigned as arrays
  • Strings can be destructively assigned as array-like objects (by index and length)

Object literals are enhanced

5.1 Property and method abbreviations

Property name and value equality can be abbreviated in an object; Methods can be written directly without function declarations

const age=18
const obj={
            age,
            fn(){}}Copy the code

5.2. Square bracket syntax enhancement – Property names can now be written to variables

1. Square bracket syntax can be written in object literals

      const name = 123;
      const obj = {
        ["age"] :18,
        [name]: "CAI Xukun"};console.log(obj);//{123: "CAI Xukun ", age: 18}
Copy the code

Default values for function parameters – You can set default values for parameters. If no parameters are passed, the default values are used

Vii. Remaining parameters and expansion operators

The residual/extension operator is also an important syntax in ES6, using three dots (…). , followed by a data structure containing the iterator interface

7.1 Remaining Parameters – Parameter variable groups

The remaining arguments can combine the extra arguments into an array, and the last position of the function parameter can be passed by… The args Settings,

7.1.1 Remaining parameters of the arrow function

For arrow functions where arguments are not available, use the remaining arguments instead of arguments to get the actual arguments.

const add = (. args) = > {
console.log(args);
};
add(1.2);
Copy the code

7.1.2 Application of the remaining parameters

  • 1. Complete the add function
  • 2. Used in conjunction with deconstruction assignment

7.2 Array Expansion operator – Converts an array into a comma-separated sequence of arguments, mainly used for function calls.

console.log(Math.min(... [3.1.2]));
Copy the code

7.2.1 Apply method to replace functions

Since the extension operator can expand an array, the apply method is no longer needed to convert the array to a function argument. The second argument to apply is an array argument.

7.2.2 Application of the Array expansion operator

  • 1. Copy the array (deep copy)
       const a = [1.2];
       const c = [...a];
       a[0] = 3;
       console.log(a);/ / (3, 2]
       console.log(c);/ / [1, 2]
Copy the code
  • 2. Merge arrays (shallow copy)
const arr1 = ['a'.'b'];
const arr2 = ['c'];
const arr3 = ['d'.'e'];

// Merge array of ES5
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]

// Merge array of ES6
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
Copy the code
  • 3. Convert a string to an array
       console.log([...'alex']);//['a','l','e','x']
       console.log('alex'.split(' '));/ / es6 before
Copy the code
  • 4. Common class arrays are converted to arrays
    4.1 arguments
       function func() {
         console.log([...arguments]);
       }
       func(1.2);

    4.2 NodeList
      console.log([...document.querySelectorAll('p')]);
Copy the code
    1. An object that implements the Iterator interface

Any object that defines an Iterator interface (see the Chapter on Iterator) can be converted to a true array using the extension operator.

let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
Copy the code

7.3 Basic Usage of object Expansion Operators

Object extension operator (…) Retrieves all traversable properties of the parameter object and copies them to the current object.

1. Expand object (deep copy object)

  • Objects cannot be expanded directly; they must be expanded in {}
  • Object expansion: List attributes, separated by commas, in a {} to form a new object
      const apple = {
        color: "Red".shape: "Ball".taste: "Sweet"};constOb = { ... apple };console.log(Ob);
      console.log(Ob === apple); //false
Copy the code

2. Merge objects. The last name of the same parent overwrites the first

3. Merge user parameters with default parameters. Write the default parameters first and user parameters last

4. Note – if the expansion is not an object, it will automatically turn it into an object, and then list its properties, like an array object

Symbol unique value

ES6’s new Symbol is a primitive value with a unique and immutable Symbol instance. Its purpose is to ensure that object attributes use unique identifiers.

//1. Use the Symbol() function to initialize
 let name1 = Symbol('liming');
 let name2 = Symbol('liming');
 console.log(name1 == name2);  //false
 
// We want to use the same symbol more than once
 let name1 = Symbol.for('name'); // Create a new one after detecting that it is not created
 let name2 = Symbol.for('name'); // Return when creation is detected
 console.log(name1 === name2); // true
 
Method: / / access to the Object. GetOwnPropertySymbols. This method returns an array of all the Symbol values used as attribute names for the current object.

 let id = Symbol("id");
 let obj = {
  [id]:'symbol'
 };
let array = Object.getOwnPropertySymbols(obj);
 console.log(array); //[Symbol(id)]
 console.log(obj[array[0]]);  //'symbol'
Copy the code

Set and Map data structures

9.1 Set data structure – Similar to an array (value = key), but without duplicate values.

Arguments to the Set constructor – Can take an array (or any other data structure with an Iterable interface such as string, arguments, NodeList, Set) as an argument for initialization.

      var s2 = new Set([1.2.3]); 
      console.log(s2, typeof s2);   //Set(3) {1, 2, 3} "object"

// 1. Add a member
      const s = new Set(a); s.add(1).add(2).add(2);
      console.log(s);/ / {1, 2}
      
// 2. Has determines whether there is a member
      const s = new Set(["ccc"."ssss"."dddd"]);
      console.log(s.has("dddd")); //true
      
// 3.delete Deletes a member
      s.delete("dddd");
      
// 4. Clear all files
      s.clear();
      
// 5. The size attribute is used to obtain the number of members, equivalent to length

// 6. Traversal operation (four methods), Set value = key
    Set.prototype.keys() : returns the traversal of the key name
    // set.prototype.values () : iterator that returns key values
    // set.prototype.entries () : Returns the traversal of key-value pairs
    /* set.prototype.foreach () : Iterates through each member with a callback function that takes two arguments, the first is the callback function and the second is to change this to refer to */
        const s = new Set(["CAI Xukun"."Li Yifeng".Jackson Yi]);
        s.forEach(function (value, key, set) {
          console.log(this);//document
          console.log(value, key, set === s);// True
       }, document);
      // Iterate in the order members are added to the collection
Copy the code

Set application

Add delete clear has forEach size add delete clear has forEach size

1. Array deduplication

  console.log([...new Set([1.2.1]]);Copy the code

2. Delete ‘abbacbd’ from the string. The Set method is used to convert a string into a de-duplicated object, which is then converted into an array, and the join method of an array is used to convert a string

       const s = new Set('abbacbd');
       console.log(s);//{'a','b','c','d'}
       console.log([...s].join(' '));
       console.log(s);

       // One line
       console.log([...new Set('abbacbd')].join(' '));
Copy the code

3. Store DOM elements

 <p>1111</p>
 <p>22222</p>
 <p>3333</p>
      // for()
      const s = new Set(document.querySelectorAll('p'));
      console.log(s);
      s.forEach(function (elem) {
        console.log(elem);
        elem.style.color = 'red';
        elem.style.backgroundColor = 'yellow';
      });
Copy the code

10. The Iterator and for… Of circulation

10.1 Iterator

Iterator is a new Iterator mechanism introduced in ES6. All data structures with Iterator interfaces can be iterated. of… To traverse.

10.2 Why the Iterator is Needed –for.. Of to traverse

Our previous traversal method was:

  • Traversal groups: for loops and forEach methods
  • Iterate over objects: for in loop

Iterator is a unified traversal method that uses Iterator’s encapsulated for.. Of to iterate over, whether it’s arrays or objects

10.3 Native Traversable (with Iterator interface)

  • An array of
  • string
  • Set
  • Map
  • arguments
  • NodeList (typically obtained with querySelectorAll)
  • General objects can use for… Iterator: in iterator: in iterator: in iterator: in iterator: in iterator: in iterator: in iterator: in iterator: in iterator: in iterator: for… Of traversal

10.2.1 for… Of traversal number group

const arr = [1.2.3];
Arr.keys () returns the traversable object of the index
      for (const key of arr.keys()) {
          console.log(key);
       }
Arr. Values () can be equivalent to arr
Arr.entries () is an array of index + value traversable objects
Copy the code

10.2.2 for… Of traverses ordinary objectsObject.entries(obj)

New methods in Es6

11.1 Adding three Es6 String Methods

1. Includes () Checks whether the string contains certain characters

// Determine the string
console.log('abc'.includes('a'.0));//true
1.The first argument ------ indicates whether the value is included2.The second argument, -----, indicates where to start the search, which is the default0The index// Determine the array
 arr = ["name".2.3.4.5.6.7.8];
 console.log(arr.includes("name"));//true
Copy the code
Application: Add parameters to the URL, check whether the URL has a question mark, if there is a question mark, yeskey=value, and then add directly to add the hyphen&key=value

2. PadStart () and padEnd() complete the length of the string at the head or end of the string itself

      console.log("abc".padStart(10."0123456789")); //0123456abc
      console.log("abc".padEnd(10."0123456789")); //abc0123456
      // The first argument is the length of the completed string (there are several), and the second argument is the element completion string to be used
      // If the second argument is omitted, Spaces are used to complete the length by default
Copy the code
Apply —- to display the date format

TrimStart () and trimEnd() clear the first or last space of the string

       const s = ' a b c ';
       console.log(s);
       console.log(s.trimStart());
       console.log(s.trimEnd());
Copy the code
Application – Form validation submission

11.2 Adding Methods to the Es6 Array (Three)

1.includes()

  • Determines whether an array contains a member
  • The second parameter indicates where the search starts, and the default value is 0
Application – Array deduplication
      const arr = [];
      for (const item of [1.2.1]) {
        if (!arr.includes(item)) {
          arr.push(item);
        }
      }
      console.log(arr); / / [1, 2]
Copy the code

2.Array.from() converts an array-like object or iterable to an Array

  • An array-like object must have a Length attribute, and the element attribute name must be a numeric value or a character that can be converted to a numeric value.

  • Iterable objects (array, string, Set, Map, NodeList, arguments).

  • Element whose attribute name is not a value and cannot be converted to a value, returns an array of length whose element value is undefined

  • The first parameter – the data object that can be converted.

  • The second argument, a map method that acts like an array, processes each element and puts the value in the returned array

  • Third argument – If the second argument is a normal callback, the third argument can change the this reference

      let a = { 
          0: "aaa".1: "bbb".2: "cccc".3: "ddd".4: "eeee".length: 5 
        };
      let array1 = Array.from(a, (value) = > value + "You look so handsome.");
      console.log(array1); / / / "aaa you really handsome", "BBB you really handsome," "CCCC you really handsome," "DDD you really handsome", "eeee you really handsome"]
Copy the code

3. Find (callback) returns the element and findIndex() returns the index

Find () : find() returns the first matched element

  • 1. The find() method executes a callback (condition statement) on each element until the condition is true, and returns undefined if it cannot be found.
  • 2. The callback takes three arguments: the value of the current element, the index of the current element, and the array itself.
     var num = [10.20.30.40.50.60.70.80.90];
     var newNum1 = num.find((item, index) = > {
       return item > 40;
     });
     console.log(newNum1); / / 50
Copy the code

FindIndex () is similar in structure, but returns the first index in the array that meets the criteria (starting at 0), not -1;

Application – Filter data
      const students = [
        {
          name: "Zhang".sex: "Male".age: 16}, {name: "Bill".sex: "Female".age: 22}, {name: "Two pockmarks of Wang.".sex: "Male".age: 32,},];console.log(students.find((value) = > value.sex === "Male"));
      console.log(students.findIndex((value) = > value.sex === "Female"));
Copy the code

11.3 Adding Two Es6 Object Methods

1.Object.assign() Merges objects

  • Object.assign(Target Object, source Object 1, Source Object 2…) : Target object
  • Object.assign is merged directly into the first parameter and returns the merged Object
Apply – merges default and user parameters
      const logUser = (userOptions) = > {
        const DEFAULTS = {
          username: "ZhangSan".age: 0.sex: "male"};const options = Object.assign({}, DEFAULTS, userOptions);
        console.log(options);
      };
      logUser();
Copy the code

2. object.keys (), object.values () and Object.entries()

  • Array keys(), values(), entries() and other methods are instance methods that return iterators
  • Object methods such as object.keys (), object.values (), and object.entries () are constructor methods that return arrays
      const person = {
        name: "Alex".age: 18};console.log(Object.keys(person)); //['name',"age"]
      console.log(Object.values(person));//["Alex", 18]
      console.log(Object.entries(person)); // Array [["name", "Alex"],["age", 18]]
Copy the code
Application – and for… of… Walk through objects together
      obj = { name: "CAI Xukun".age: "18".hobby: ["Sing"."Writing songs"."Dance"]};console.log(Object.entries(obj));

      for (key of Object.entries(obj)) {
        console.log(key[0], key[1]);
      }
Copy the code

I Promise you

  • Promise, a new asynchronous programming solution in ES6, is a constructor that passes through the codenew Promise()Generates an instance object. The essence is to use the corresponding callback function through the state call.
  • The Promise object can represent asynchronous operations as a synchronous flow, avoiding layers of nested callback functions (callback hell).

12.1 Basic Usage

Step 1: Create a Promise instance object and pass in the executor function, which executes simultaneously

//Promise is a constructor
let p = new Promise(executor)
Copy the code

The executor executor function takes two arguments, resolve and reject, that change the Promise state. Once the state is changed, it is not reversible.

  1. Pending: Indicates the initial status.
  2. Someday (Resolved): As long as the resolve function is called, the operation is successful.
  3. Rejected: The operation fails as long as the Rejected function is called.
  4. State success or failure calls the corresponding success or failure callback..then(success(){},failed(){})
let p=new Promise((resolve,reject)={
  Execute resolve (reject), reject (synchronous), and then call all three methods */ based on the status of the task
})
Copy the code

12.2 Promise.prototype.then() method use (can be used multiple times)

  • The then method takes two functions as arguments, the first a callback if the Promise succeeds and the second a callback if the Promise fails. Only one of the two functions will be called.

  • The then() method returns a new Promise object. The state of the Promise is determined by the return value of the callback function executed in the THEN. The return value is a non-PROMISE object and its state is successful

// Promise object structure;
{
 [[PromiseState]]: "fulfilled"
// The first is determined by resolve or reject. The state of the object returned by then is determined by the value returned by the current function
         
[[PromiseResult]]: "222"
// The result is the value of return after the current Promise object calls then,
}      
Copy the code
  • Arguments can be passed to the then method of the next promise object through the then method of the previous promise object, and the passed arguments are returned to the then method of the next Promise object by return.
  • If the first call, reject (), calls the failed callback, and returns a new promise state with success, what if we want it to fail, throwing an error inside the callbackthrow new Error(err);

Conclusion: Consequences of executing reject() :

Change the state of the current Promise object to failure, leaving all subsequent Promise objects as successes.

As long as the call procedure uses reject(), the raw data is no longer available;

After use in front of the reject, if want to also follow behind state to fail, to reject () in the corresponding failure function throw an Error in the statement: throw new Error (err);

If you want to change the result of a Promise returned by the current call to then, add a return to the current THEN that returns the desired result.

Either the arguments passed in the successful or failed callback of the previous Promise object are passed to the successful callback of the next Promise object.

12.2 Promise.prototype.catch() method use

  • .catch() specifically listens for failed callbacks
  • If you need to listen separately, use.then().catch()Method uses chained programming, where the promise state fails but there is no listener for that failure

  • The difference from the second argument to the THEN method is that the catch method catches the exception in the then method of the previous Promise object (which also includes the successful callback method).

Js exception handling

The use of try{}catch{} to handle exceptions can ensure that the program is not interrupted, and the cause of the error can be recorded for subsequent optimization iteration update.

try{unexpected code that may be encountered}catch(e) {block of code that caught the error}Copy the code

Catch features:

  • (1) As with THEN, when modifying the promise state, parameters can be passed to the callback function in the catch method;
  • (2) Like then, the same Promise object can call catch methods multiple times, and all catch methods will be executed when the promise object is in the state.
  • (3) Like then, catch returns a new promise object after each execution
  • (4) Like the then method, the previous promise object can also successfully pass parameters to the next promise.but, and either the arguments passed in the successful or failed callback of the previous Promise object are passed to the successful callback of the next Promise object.
  • (5). Like then, if a catch method returns a Promise, the value of the return Promise is passed to the next catch method.
  • (6). The difference between the catch method and the then method is that the catch method can catch the exception in the then method of the previous Promise object.

12.3 Use of promise.all () method

Parameters:

    1. The all method receives oneAn array of.
    1. If there are multiple Promise objects in the array, onlyAll successfulThe then method is executed and all successful results are repackaged into an array and returned to us in the order they were added.
    1. If the array is not a Promise object, then the then method is executed directly

Returns:

  • 1. The all method returns a new Promise object

  • 2. All successful Promise returns are saved into a new array in the order they were passed in

  • 3. There is one Promise in the array that will fail if it fails, and only if it succeeds will it succeed

  • Application scenario: Batch loading succeeds or fails together

12.4 Use of promise.race () method

  • 1. The race method receives an array,
  • 2. If there are multiple Promise objects in the array, the first to return the state will be accepted, and the last to return will be discarded
  • 3. If the array is not a Promise object, the then method is executed directly
  • Application scenario: Interface debugging and timeout processing

Wrap a promise object for both the timeout function and the loading function, then write this object to race, and then write the handler. If no resource is obtained within 5 seconds, the handler will timeout

12.5 Use of the promise.resolve () and promise.reject () methods

Promise.resolve() returns a successful Promise object

      p = Promise.resolve("success");
      console.log(p);

      /* [[PromiseState]]: "fulfilled" [[PromiseResult]]: "success" */
Copy the code

Promise.reject() returns a failed Promise object

      p = Promise.reject("failed");
      p.catch((err) = > console.log(err));
      console.log(p);

      /* [[PromiseState]]: "rejected" [[PromiseResult]]: "failed" */
Copy the code

Promise encapsulates the network requestnetworkThat piece

Summary: How does Promise work?

  • Buy food (20 minutes) –> cook (30 minutes) –> deliver food (10 minutes) –> notice; Are time-consuming asynchronous tasks
  • Create a number of functions (buy food, cook food, send food, or just one function) that take resolve and execute resolve inside the timer to send the completed task.
new Promise(shopping). Then ((Buy good food) = >{
    return new Promise(cook); }).then((The best meal) = >{
    return new Promise(dinner); }).then((Meals results) = >{wife kiss a (); }).catch(err= >throw new Error(err))
Copy the code
// Write a task schedule
functionBuy vegetables (Resolve to reject) {
    setTimeout(function(){
        resolve(['Tomato','eggs','rape']);
    },3000)}functionTo cook (resolve, reject){
    setTimeout(function(){
        // Proceed to the next step of the finished meal.Resolve ({staple food:'rice'Cuisine: ['Scrambled eggs with tomatoes','Stir-fried rape']})},3000)}functionSend meal (Resolve to reject){
    // Proceed to the next step
    resolve("The wife's moo moo.");
}
functionCall me (){
    // Call me for the next stepGive the babysitter100Yuan bonus; }// Start the task
// Tell the nanny to help me do a few coherent things, first go to the supermarket to buy food
new Promise(shopping)// Cook with bought food
.then((Buy good food) = >{
    return new Promise(cook); })// Take the meal to wife's company
.then((The best meal) = >{
    return new Promise(dinner); })// Call me after the delivery
.then((Meals results) = >{call me (); })Copy the code
  • Keep in mind that if our subsequent tasks are asynchronous, we must return a new Promise object.
  • If the subsequent task is a synchronization task, you only need to return a result.
  • In our example above, except for the call that tells me it’s a synchronous task, the rest are asynchronous tasks, and the asynchronous task returns a Promise object.

Async functions

Async and await are syntactic sugars of Promise async is a modification of a function that causes a function to return a Promise instance. Await is to wait for a Promise instance to succeed

  • 1. After adding an async modifier to a function, the result of execution is a successful promise object. We can use then directly after the function execution statement.
      async function foo() {
        //1. Return successful
        //return Promise.resolve();
        return 1;

        // 2. Return failed
        // return Promise.reject();
        // throw new Error(" I am wrong ");
      }
 
      foo().then((res) = > {
        console.log(res); / / 1
      });
Copy the code
  • 2. Await can only be executed inside async functions, otherwise an error will be reported, meaning to wait for a promise instance to succeed.
Interview question: Write a sleep function that waits 1000ms before doing anything else?
  • Plan 1: Use a timer
  • Scheme 2: The function returns a Promise object
      function sleep(interval = 5000) {
        return new Promise((resolve) = > {
          setTimeout(resolve, interval);
        });
      }
      sleep(2000).then(() = > {
        console.log("I execute after 2000ms");
      });
Copy the code
  • Option 3: Use the await statement
      function sleep(interval = 1000) {
        return new Promise((resolve) = > {
          setTimeout(resolve, interval);
        });
      }
      (async function () {
        // It takes eight seconds to buy food
        await sleep(8000);
        // Let me know when the vegetables come back
        console.log("I execute after 1000ms.");
        // It takes two seconds to cook
        await sleep(2000);
        // Let me know when dinner is ready
        console.log("I execute after 2000ms");
        // 5s is required for eating
        await sleep(5000);
        // Let me know when you finish eating
        console.log("I execute after 5000ms"); }) ();Copy the code

The grammar of Module

A module is an independent file. All variables inside the file are not available externally. If you want outsiders to be able to read a variable inside a module, you must use the export keyword to output that variable. Here is a JS file that uses the export command to output variables.

Variable or function loading

  • If you want to export a variable or function, add export at the top of it, and import a variable from another module
Export Sets the external interface
export var name='CAI Xukun'
export function multiply() {}
export { firstName, lastName, year }

// the import command loads the module (with the same external and internal interface names).
// The input variables of the import command are read-only. It is not allowed to rewrite the interface in the module loading script.
// The import command is promoted to the top of the module and executed first.
import { firstName, lastName, year } from './profile.js'
Copy the code

Integral loading of modules —export defaultThe command

For the convenience of users, they can load modules without knowing the name of the variable or function they want to load.

// export-default.js
export default function () {
  console.log('foo')}Copy the code

The above code is a module file, export-default.js, whose default output is a function. The import command can specify any name for the anonymous function when the module is loaded by other modules.

// import-default.js
import customName from './export-default'
customName() // 'foo'
Copy the code