es6 generator and Promise (es6 study notes 04)

Preface: This article mainly records generators and Promises

One, the generator

The generator is actually a special function.

生成器函数: It is an ** asynchronous programming ** solution provided by es6 . The syntax behavior is completely different from traditional functions.

异步编程: Simply put, it is a pure callback function, such as node, fs, ajax, MongoDB, etc.

1.1 Declaration of the generator

Add * in front of the function name

//声明特殊
function * hong(){
    
    
     console.log("你好,红红"); //并不会直接输出
}
//执行特殊
let iterator = hong();
terator.next();  //调用.next才会输出“你好,红红”(迭代器)

Insert picture description here

Note : The direct call of the execution statement will not be executed, it must be .nextcalled by method

1.2 Function code separator-yield

Divide the inside of the function into segments

//函数代码的分隔符 yield的使用
function *lv(){
    
    
    console.log(111);
    yield '我分隔';
    console.log(222);
    yield '我分隔,到我停止';
    console.log(333);
    yield '我再分隔';
    console.log(444);
}
let lvtor = lv();
lvtor.next();    //调用一次,输出111
lvtor.next();    //接着调用,接着输出222
lvtor.next();    //接着调用,接着输出333
//console.log(lvtor.next());  执行获取迭代器的对象

//遍历
for(let v of lv()) {
    
    
     console.log(v);
}

Separate results above :
Insert picture description here

Traverse results :

Insert picture description here

1.3 Parameter passing of generator function

The next parameter is used as the return value of the previous yield statement

//生成器函数的传参
function * mini(arg){
    
    
     console.log(arg);
     let one = yield 111;
     console.log(one);
     let two = yield 222;
     console.log(two);
     let three = yield 333;
     console.log(three);
}

let itor = mini('AAA');
console.log(itor.next());
//next方法可以传入实参
console.log(itor.next('BBB')); //为yield111传入参数
console.log(itor.next('CCC'));
console.log(itor.next('DDD'));

Output result:
Insert picture description here

1.4 Generator small example

(1) Intermittent call

111 is output after 1s, 222 is output after 2s, and 333 is output after 3s

//用生成器实现
        function one(){
    
    
            setTimeout(() => {
    
    
                console.log(111);
                it.next();   //使其继续执行下一个
            },1000)
        }
        function two(){
    
    
            setTimeout(() =>{
    
    
                console.log(222);
                it.next();
            },2000)
        }
        function three(){
    
    
            setTimeout(()=>{
    
    
                console.log(333);
                it.next();
            },3000)
        }

        function * green(){
    
    
            yield one();
            yield two();
            yield three();
        }
        //调用
        let it = green();
        it.next();
(2) Acquisition of simulation data

You must first obtain user information, then obtain order data based on user information, and then obtain product data based on order data. Since they are obtained layer by layer, they can be implemented with a generator.

//模拟获取 用户数据 订单信息 商品数据
        function getUser(){
    
    
            setTimeout(()=>{
    
    
                let data = '用户信息';
                //调用next方法,并将数据传入
                getor.next(data);
            },1000)
        }
        function getOrder(){
    
    
            setTimeout(()=>{
    
    
                let data = '订单数据'
            },1000)
        }
        function getGoods(){
    
    
            setTimeout(()=>{
    
    
                let data = '商品数据'
            },1000)
        }
        //定义生成器函数
        function *datas(){
    
    
            yield getUser();
            yield getOrder();
            yield getGoods();
        }
        //调用生成器函数
        let getor = datas();
        getor.next();
  • The next method is used to pass parameters.

二、Promise

Promise is an asynchronous programming solution introduced by es6. Syntactically, Promise is a constructor that encapsulates asynchronous operations and can obtain the results of their success or failure.

  • Promise constructor:Promise(excutor){}
  • Promise.prototype.thenmethod
  • Promise.prototype.catchmethod

When there are many asynchronous processes, promises can be used to reduce indentation.

2.1 Use of Promise's then method

  • If the status is successful, call the first callback function of then, otherwise call the second one.
//实例化 Promise对象
const h = new Promise(function(resolve,reject){
    
       //这里定义的两个参数一般是这两个,潜规则
setTimeout(function(){
    
    
       let data = '数据读取成功啦';
       resolve(data);  //调用resolve,表示读取成功

        //let err = '数据读取失败了';  调用reject,表示读取失败
        //reject(err);
     },1000)
 });

//调用promise 对象的then方法
h.then(function(value){
    
    
      console.log(value);    //成功时执行
},function(reason){
    
    
      console.error(reason);  //失败时执行
})

Then call the method, the method returns the result then is the Promise object, the object status by the callback function of 执行结果the decision

  1. If the result returned in the callback function is a non-Promise type property (including undefined if there is no return value), the status is success, and the return value is the success value of the object.
  2. Is a Promise object, the content of the object is returned
  3. Throw error
//then 方法解析
        const hh = new Promise((resolve,reject) =>{
    
    
            setTimeout(()=>{
    
    
                resolve('红红的数据');
                //reject('出错啦');
            },1000)
        });
        
        const result = hh.then(value =>{
    
    
            console.log(value);
            //1.非Promise类型的属性
            //return 'hhhhhh';
            //2.是promise对象
            //return new Promise((resolve,reject)=>{
    
    
                //resolve('ok');
                //reject('error');
            //});
            //3.抛出错误
            throw new Error('出错了');
        },reason =>{
    
    
            console.warn(reason);
        });
  • If the return result of then is a Promise, you can use chain call
p.then(value =>{
    
    },reason=>{
    
    }).then(value=>{
    
    },reason=>{
    
    })

2.2 Use Promise to encapsulate and read files

The following is written in a file named Promise reading.js :

//1.引入 fs 模块
const fs = require('fs');

//2.调用方法读取文件
// fs.readFile('./data/study.md',(err,data) =>{
    
    
    //如果失败,抛出错误
    // if(err) throw err;
    //如果没有出错,则输出内容
    // console.log(data.toString());
// })

//3.使用Promise封装
const p = new Promise(function(resolve,reject){
    
    
    fs.readFile("./data/study.md",(err,data)=>{
    
    
        //判断如果失败
        if(err) reject(err);
        //如果成功
        resolve(data);
    });
});
//调用then方法
p.then(function(value){
    
    
    console.log(value.toString());
},function(reason){
    
    
    console.log("读取失败啦!");
});
  • In the console input node Promise读取文件.jsyou can view the results.

2.3 Use Promise to encapsulate ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise封装ajax</title>
</head>
<body>
    <script>
        //接口地址 :https://api.apiopen.top/getJoke
     const p = new Promise((resolve,reject)=>{
     
       //封装
        //1.创建对象
        const xhr = new XMLHttpRequest();

        //2.初始化
        xhr.open("GET","https://api.apiopen.top/getJoke");

        //3.发送
        xhr.send();

        //4.绑定事件,处理响应结果
        xhr.onreadystatechange = function(){
     
     
            //判断
            if(xhr.readyState === 4){
     
     
                //判断响应状态码200-299
                if(xhr.status >= 200 && xhr.status <300){
     
     
                    //表示成功
                    resolve(xhr.response);
                }else{
     
     
                    //如果失败
                    reject(xhr.status);
                }
            }
        }
    })

    //指定回调  在这里做数据的处理
    p.then(function(value){
     
     
        console.log(value);
    },function(reason){
     
     
        console.log(reason);
    });
    </script>
</body>
</html>

2.4 Promise realizes the reading of multiple file contents

//引入fs
const fs = require("fs");

const h = new Promise((resolve,reject)=>{
    
    
    fs.readFile("./data/study.md",(err,data)=>{
    
    
        resolve(data);
    });
});
//调用
h.then(value =>{
    
    
    return new Promise((resolve,reject)=>{
    
    
        fs.readFile('./data/红红.md',(err,data)=>{
    
    
            resolve([value,data]);
        });
    })
}).then(value => {
    
    
    return new Promise((resolve,reject)=>{
    
    
        fs.readFile('./data/绿绿.md',(err,data)=>{
    
    
            //压入
            value.push(data);
            resolve(value);
        });
    })
}).then(value =>{
    
    
    console.log(value.join('\r\n'));
});

result:

Insert picture description here

2.5 Promise's catch method

It is syntactic sugar for the then method, used to set the failed callback

p.catch(function(reason){
    
    
    console.warn(reason);
});

Guess you like

Origin blog.csdn.net/weixin_48931875/article/details/113528068