jses6语法:Iterator遍历器 promise async函数

更新日期: 2020-10-02阅读: 1.3k标签: es6

一, Iterator遍历器

他是一种接口,为不同的数据结构体用统一的访问机制

var a = makeIterator([‘a‘, ‘b‘]);

console.log(a.next());  // a  false
console.log(a.next());  // b false
console.log(a.next());  // undefined true

function makeIterator(array) {
    var nextIndex = 0;
    return {
        next: function () {
            return nextIndex < array.length ? { value: array[nextIndex++], done: false }
                : { value: undefined, done: true }
        }
    }
}


1, 默认接口

接口部署在数据结构的Symbol.Iterator属性,或者说一个数据结构只要具备Symbol.Iterator属性就认为是可以遍历的

var obj = {
    [Symbol.Iterator]: function () {
        return {
            next: function () {
                return {
                    value: 1,
                    done: true,
                }
            }
        }
    }
}

var a = obj[Symbol.Iterator]().next()
console.log(a);  

// 数组有默认的[Symbol.Iterator]
let arr = [‘a‘,‘b‘,‘c‘];
let ter = arr[Symbol.iterator]();

console.log(ter.next());
console.log(ter.next());
console.log(ter.next());
console.log(ter.next());


二, Promise

异步编程的解决方案

已完成 fulfilled 进行中 pending 失败 rejected


1, 基本语法

Promise就是一个构造函数,可以生成实列

var per = new Promise(function(resolve,reject){

    if(true){
        resolve // 数据
    }else{
        reject // 错误信息
    }
});

// 实列生成以后  可以用then方法处理resolve状态和reject状态
per.then(function(value){
    // success
},function(error){
    // error
})


2, Promise会立即执行

let per = new Promise(function(resolve, reject){
    console.log(‘立即执行‘); // 1
    resolve();
})

per.then(function(){
    console.log(‘resolved‘); // 3
})
console.log(‘hello‘); // 2


3, 请求数据

// 1、实列化一个对象
function getJson(url) {
    var per = new Promise(function (resolve, reject) {
        // 请求数据的ajax
        var ajax = new XMLHttpRequest();
        ajax.open(‘get‘, url);
        ajax.send();
        // 监听
        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4) {
                if (ajax.status === 200) {
                    resolve(ajax.responseText);
                } else {
                    reject(new Error(ajax.status));
                }
            }
        }
    })
    return per;
}

var a = getJson(‘./data/banner.json‘)
console.log(a);

getJson(‘./data/banner.json‘).then(function(json){
    console.log(json);
},function(text){
    console.log(text);
})


4, then

getJson(‘./data/banner.json‘).then(function(json){
   console.log(json);
},function(text){
   console.log(text);
})


5, 链式写法

getJson(‘./data/banner.json‘)
.then(function (json) {
    return getJson(‘./data/1.txt‘);
})
.then(function(){
    console.log(‘我的‘);
},function(){
    console.log(‘你的‘);
})


6, catch

用于指定发生错误时的回调函数

getJson(‘./data/banner.json‘).then(function (post) {
    console.log(post);
}).catch(function (error) {
    console.log(‘错误:‘, error);
})


7, all

将多个Promise实列包装成一个新的Promise实列

const p = Promise.all([p1,p2,p3]);
//这个方法接受一个数组作为参数,p1,p2,p3都是Promise实列

const per = [1, 2, 3].map(function (item) {
    return getJson(‘./data/‘ + item + ‘.txt‘); // ‘./data/1.json‘
})

Promise.all(per).then(function (post) {
    console.log(post);
}).catch(function (reason) {
    console.log(reason);
})


8, race

将多个Promise实列包装成一个新的Promise实列

const p = Promise.race([p1,p2,p3]);

const p = Promise.race([
    getJson(‘./data/banner1.json‘),
    new Promise(function (resolve, reject) {
        setTimeout(() => reject(new Error(‘错误‘)), 2000)
    })
])
p.then(console.log(‘1‘))
    .catch(console.error);


三, async函数

他是Generator函数语法糖,让异步更简单

function*a(){
    yield 1;
}
var n = a();
n.next();


1, 改成async函数,就是用async把星号替换掉,用await把yield替换掉

async function a(){
    var h = await 1;
    console.log(h);
}
a();

这个函数返回的是Promise对象,就可以使用then添加回调。


2, await

正常的情况下await后面是一个Promise对象,返回该对象的结果,如果不是Promise对象,返回的是这个值

async function f(){
    return await 123;
}
f().then(v=>console.log(v))


3, 错误处理

也就是 async 出错,Promise处于reject状态

async function f() {
    await new Promise(function (resolve, reject) {
        throw new Error(‘出错了‘);
    })
}
f().then(v => console.log(v))
.catch(e => console.log(e));

链接: https://www.fly63.com/article/detial/9806

es6 箭头函数的使用总结,带你深入理解js中的箭头函数

箭头函数是ES6中非常重要的性特性。它最显著的作用就是:更简短的函数,并且不绑定this,arguments等属性,它的this永远指向其上下文的 this。它最适合用于非方法函数,并且它们不能用作构造函数。

详解JavaScript模块化开发require.js

js模块化的开发并不是随心所欲的,为了便于他人的使用和交流,需要遵循一定的规范。目前,通行的js模块规范主要有两种:CommonJS和AMD

js解构赋值,关于es6中的解构赋值的用途总结

ES6中添加了一个新属性解构,允许你使用类似数组或对象字面量的语法将数组和对象的属性赋给各种变量。用途:交换变量的值、从函数返回多个值、函数参数的定义、提取JSON数据、函数参数的默认值...

ES6中let变量的特点,使用let声明总汇

ES6中let变量的特点:1.let声明变量存在块级作用域,2.let不能先使用再声明3.暂时性死区,在代码块内使用let命令声明变量之前,该变量都是不可用的,4.不允许重复声明

ES6的7个实用技巧

ES6的7个实用技巧包括:1交换元素,2 调试,3 单条语句,4 数组拼接,5 制作副本,6 命名参数,7 Async/Await结合数组解构

ES6 Decorator_js中的装饰器函数

ES6装饰器(Decorator)是一个函数,用来修改类的行为 在设计阶段可以对类和属性进行注释和修改。从本质上上讲,装饰器的最大作用是修改预定义好的逻辑,或者给各种结构添加一些元数据。

基于ES6的tinyJquery

Query作为曾经Web前端的必备利器,随着MVVM框架的兴起,如今已稍显没落。用ES6写了一个基于class简化版的jQuery,包含基础DOM操作,支持链式操作...

ES6 中的一些技巧,使你的代码更清晰,更简短,更易读!

ES6 中的一些技巧:模版字符串、块级作用域、Let、Const、块级作用域函数问题、扩展运算符、函数默认参数、解构、对象字面量和简明参数、动态属性名称、箭头函数、for … of 循环、数字字面量。

Rest/Spread 属性_探索 ES2018 和 ES2019

Rest/Spread 属性:rest操作符在对象解构中的使用。目前,该操作符仅适用于数组解构和参数定义。spread操作符在对象字面量中的使用。目前,这个操作符只能在数组字面量和函数以及方法调用中使用。

使用ES6让你的React代码提升到一个新档次

ES6使您的代码更具表现力和可读性。而且它与React完美配合!现在您已了解更多基础知识:现在是时候将你的ES6技能提升到一个新的水平!嵌套props解构、 传下所有props、props解构、作为参数的函数、列表解构

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!