模块、ES6 模块与 CommonJS 模块的差异、Promise

213 阅读3分钟

export

ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。
模块功能主要由两个命令构成:`export``import``export`命令用于规定模块的对外接口,(模块导出)
`import`命令用于输入其他模块提供的功能。(模块导入)

导出:
export var name = "lily";
export function showMsg(){
    console.log("tom")
}
//导入
import{name,showmsg} from "text.js"//在text.js中导入
console.log("name");
showname();


`export default`命令,为模块指定默认输出。
//导出文件
export default function showMsg(){
    console.log()
}
//导入文件
// import {name,showmsg} from "text.js"
import showMsg from './text.js';
console.log(name);
showname();

export加上default之后不用加{}直接文件路径即可,通常用在一个文件只导出一个模块

ES6 模块与 CommonJS 模块的差异

-   CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。
-   CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。
-   CommonJS 模块的`require()`是同步加载模块,ES6 模块的`import`命令是异步加载,有一个独立的模块依赖的
解析阶段。

Promise

`Promise`一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果。
Promise 一个对象,从它可以获取异步操作的消息(返回值是一个对象)。(放异步操作结果的一个容器)
`Promise`对象:一个构造函数
`Promise`对象代表一个异步操作,有三种状态:`pending`(进行中)、`fulfilled`(已成功)和`rejected`(已失败)

`Promise`对象的两个特点:
    对象的状态不受外界影响
    一旦状态改变,就不会再变,任何时候都可以得到这个结果。

`Promise`构造函数接受一个函数作为参数,该函数的两个参数分别是`resolve``reject`
    `resolve`函数的作用是,将`Promise`对象的状态从“未完成”变为“成功”(即从 pending 变resolved),在异步
操作成功时调用,并将异步操作的结果,作为参数传递出去;
    `reject`函数的作用是,将`Promise`对象的状态从“未完成”变为“失败”(即从 pending 变为rejected),在异步
操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

`Promise`实例生成以后,可以用`then`方法分别指定`resolved`状态和`rejected`状态的回调函数。
`then`方法可以接受两个回调函数作为参数。
    第一个回调函数是`Promise`对象的状态变为`resolved`时调用,
    第二个回调函数是`Promise`对象的状态变为`rejected`时调用

//语法
const promise = new Promise(function (resolve, reject) {
    // 内容(方法)
    if (/* 异步操作成功 */) {
        resolve(value);
    } else {
        reject(error);
    }
});


//异步加载图片实例:
function loadImageAsync(url) {
  var newimg= new Promise(function(resolve, reject) {//创建promise对象
        const image = new Image();//定义图片对象
    image.onload = function() {
      resolve(image);//成功传出正常图片
    };
    image.onerror = function() {
      reject(new Error('在此网址中没有找到图片 ' + url));//失败执行
    };
    image.src = url;//传出图片
  });
  return newimg;
}


//promise使用Ajax:
const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('出错了', error);
});

catch():
.catch()方法:.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 处理 getJSON 和 前一个回调函数运行时发生的错误
  console.log('发生错误!', error);
});

all():
`Promise.all()`方法用于将多个 Promise 实例,包装成一个新的 Promise 

// 生成一个Promise对象的数组
const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
  return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});