ES6

54 阅读2分钟

Promsie

定义

1.执行异步任务
2.避免回调地狱

实例

var myFirstPromise = new Promise(function(resolve, reject){
 //当异步代码执行成功时,我们才会调用resolve(...), 当异步代码失败时就会调用reject(...) 
//在本例中,我们使用setTimeout(...)来模拟异步代码,实际编码时可能是XHR请求或是HTML5的一些API方法. 
setTimeout(function(){
     resolve("成功!"); //代码正常执行!
     }, 250); 
 });
     
     myFirstPromise.then(function(successMessage){
     //successMessage的值是上面调用resolve(...)方法传入的值.
     //successMessage参数不一定非要是字符串类型,这里只是举个例子   
     document.write("Yay! " + successMessage); 
     });

封装Promise

    function timeout(delay = 1000) {
      return new Promise(resolve => setTimeout(resolve, delay));
    }
    timeout(2000)
      .then(() => {
        console.log("houdunren.com");
        return timeout(2000);
      })
      .then(value => {
        console.log("hdcms.com");
      });

异步与等待(async和await)

async

语法

async function name([param[, param[, ... param]]]) { statements }
  • name: 函数名称。
  • param: 要传递给函数的参数的名称。
  • statements: 函数体语句。

返回值

async function helloAsync(){
      return "helloAsync";
} 

console.log(helloAsync()) // Promise {<resolved>: "helloAsync"}
helloAsync().then(v=>{
    console.log(v); // helloAsync 
 })

await

await 操作符用于等待一个 Promise 对象, 它只能在异步函数 async function 内部使用。

语法

[return_value] = await expression;

返回值

function testAwait (x) {
   return new Promise(resolve => {
    setTimeout(() => {
        resolve(x);
    }, 2000); });
}
async function helloAsync() {
    var x = await testAwait ("hello world");
    console.log(x);
} 
helloAsync ();
// hello `world`

迭代器

可迭代对象都拥有迭代器 (可以被for of 遍历对象都是可迭代对象)String Array Map 获取迭代对象

var itr =arr [Symbol.iterator]()

通过next方法进行迭代

    itr.next()

    {value:"xxx",done:false}
    .....
    {value:undefined,done:true}

生成器

普通函数前面添加 *
通过yield关键来控制生成
最终函数执行 返回一个可迭代元素
function *range(start,end,step=1){
   while(start<step){
   yield start;
  start+=step;
   }
}
var list = range(1,100);//生成一个1-100的可迭代元素
list = [...list]//转换为数组

代理(proxy)

proxy在目标对象的外层搭建了一层拦截,外界对目标对象的某些操作,必须通过这层拦截

var proxy = new Proxy(target, handler);

new Proxy()表示生成一个Proxy实例,target参数表示所要拦截的目标对象,handler参数也是一个对象,用来定制拦截行为

var target = {
name: 'poetries'
};
var logHandler = {
get: function(target, key) {
  console.log(`${key} 被读取`);
  return target[key];
},
set: function(target, key, value) {
  console.log(`${key} 被设置为 ${value}`);
  target[key] = value;
}
}
var targetWithLog = new Proxy(target, logHandler);

targetWithLog.name; // 控制台输出:name 被读取
targetWithLog.name = 'others'; // 控制台输出:name 被设置为 others

console.log(target.name); // 控制台输出: others

Proxy 实例也可以作为其他对象的原型对象

var proxy = new Proxy({}, {
  get: function(target, property) {
    return 35;
  }
});

let obj = Object.create(proxy);
obj.time // 35

Proxy的作用

对于代理模式 Proxy 的作用主要体现在三个方面

  • 拦截和监视外部对对象的访问
  • 降低函数或类的复杂度
  • 在复杂操作前对操作进行校验或对所需资源进行管理