Point review of the papers focus on the front end of knowledge and async function of module --ES6

async function

ES2017 standard introduces async function, so that the asynchronous operation becomes more convenient.

async function is a function of syntactic sugar Generator

What is syntactic sugar?

Grammar does not mean that add new features to a computer language, but only for humans more "sweet" in. Syntactic sugar often provides programmers with a more practical way of coding, coding style conducive to a better, more readable. But it did not add anything new to the language

When async function is to use an asterisk Generator function (*) replaced async, will replace yield to await, and nothing more

async Function Generator function of the difference between:

(1) built-in actuator.

Generator function must be executed by the actuator, and async function comes actuators. In other words, the implementation of async function and normal function exactly the same, as long as the line.

(2) better semantics.

async and await, compared with an asterisk and yield, semantics more clear. There async function representing asynchronous operation, await expressed immediately following expression needs to wait for the results.

(3) Normally, await a command followed Promise object. If not, it will be turned into an object immediately resolve the Promise.

(4) The return value is Promise.

async function return value is an object Promise, than Generator function return value is much more convenient Iterator objects. You can then specify the next step method of operation.

Furthermore, async function can be seen as multiple asynchronous operation, packed into a Promise object, and await command is then command syntax sugar inside.

Usage is as follows:

let task1 = function(){
    return new Promise((res, rej)=>{
        setTimeout(() => {
            res("完成task1");
        }, 1000);
    });
}
let task2 = function(str){
    return new Promise((res, rej)=>{
        setTimeout(() => {
            res(str+"完成task2");
        }, 2000);
    });
}
let task3 = function(str){
    return new Promise((res, rej)=>{
        setTimeout(() => {
            res(str+"完成task3");
        }, 3000);
    });
}
async function f() {
    let t1 = await task1();  //在这里await返回的是promise中resolve方法的参数
    console.log(t1, typeof t1);  //完成task1 string
    let t2 = await task2(t1);
    console.log(t2);
    return task3(t2);  //最后用return,表示将结果作为返回的Promise对象的resolve的参数
}
f().then(data=>{console.log(data)});  //完成task1完成task2完成task3

Error Handling

If the latter error await asynchronous operation, then the object is equivalent to the async Promise function returns the reject. Error prevention method, which is placed into the try ... catch block.

async function main() {
  try {
    const val1 = await firstStep();
    const val2 = await secondStep(val1);
    const val3 = await thirdStep(val1, val2);

    console.log('Final: ', val3);
  }
  catch (err) {
    console.error(err);
  }
}

Module

ES6 modules automatically use strict mode, whether you have add "use strict" in the module header ;.

Function block mainly composed of two commands: export and import.

export command specified external interface module.

import command input function provided by other modules.

export

A module is a stand-alone document. All variables inside the file, can not get outside. If you want to be able to read an external variable inside the module, you must use the export keyword output variable.

export output a traversal wording:

// profile.js
export var firstName = 'Michael';
export var lastName = 'Jackson';
export var year = 1958;

Writing two (recommended):

// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export {firstName, lastName, year};
//跟上面写法等价,推荐这种写法。

Can be used as keywords Rename:

function v1() { ... }
function v2() { ... }

//export 内部参数 as 外部调用名
export {
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
};

Interface export statement output value corresponding thereto is dynamic binding relationship, i.e., through the interface, may take the values ​​in real time inside the module.

export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);
//上面代码输出变量foo,值为bar,500 毫秒之后变成baz。

export command module can appear anywhere, as long as it can be in the top level module. If you are in block-level scope, the error will be below the import command as well.

import

After defining the external interface module using the export command, other JS file you can load the module with the import command.

The following code import commands for loading profile.js file, and from the input variables. import command accepts a pair of braces, which specifies the variable name from other imported modules. Braces inside the variable name must be the same as the imported modules (profile.js) the name of the external interface.

// main.js
import {firstName, lastName, year} from './profile';

If you want to re-enter the variable a name, import commands to be used as a keyword, variable input renamed.

//import 外部变量 as 内部参数
import { lastName as surname } from './profile';

Note, import command with a lifting effect, will be promoted to head the entire module, executed first.

foo();

import { foo } from 'my_module';
//import的执行早于foo的调用。这种行为的本质是,import命令是编译阶段执行的,在代码运行之前。

In addition to specifying an output value is loaded, you can use the whole load, which specifies an object with an asterisk (*), all output values ​​are loaded on top of the object. Note that the object module where the whole load, may not be changed at runtime. The following versions are not allowed.

import * as circle from './circle';

// 下面两行都是不允许的
circle.foo = 'hello';
circle.area = function () {};

export default

Using the import command when the user needs to know the name of the variable or function name to be loaded, or can not be loaded.

In order to provide convenience to users, so that they do not read the documentation can load modules, it is necessary to use export default command to specify the default output for the module.

// export-default.js
export default function () {
  console.log('foo');
}

When other modules to load the module, import command can specify any name for the anonymous function.

// import-default.js
import customName from './export-default';
customName(); // 'foo'

export default command before non-anonymous function, is also possible. The following code, the function name foo foo function, the external module is invalid. When loaded, as if an anonymous function to load.

// export-default.js
export default function foo() {
  console.log('foo');
}

// 或者写成
function foo() {
  console.log('foo');
}
export default foo;

export default command is used to specify the default output module. Obviously, a module can have only one default output, export and therefore can only be used once default command. So, import parentheses after the command was not increased, since only be unique to export default command.

Guess you like

Origin www.cnblogs.com/simpul/p/11020250.html