Promise, dimensionality increase and dimensionality reduction of arrays

Introduction to promise

  • ES6 tutorial portal: http://es6.ruanyifeng.com/#docs/promise
  • What is Promise?
    • Promise is a constructor, used to create Promise objects
      • Promise object: can be understood as a container that handles asynchronous operations
  • Promise essence 不是控制异步代码的执行顺序(无法控制) , 而是控制异步代码结果处理的顺序
  • Promise role: solve callback hell
    • Callback hell: asynchronous callbacks are nested

promise use

  • manual
  1. Create a promise instance object
 let p = new Promise( (resolve,reject)=>{
    
     //异步操作 } )

  1. Call the then method of the instance object
 p.then(data=>{
    
     //处理成功数据 } , err=>{ //处理失败结果 })
  • Promise has three states
    • pending (in progress)
    • fulfilled
    • rejected (failed)
  • There are only two cases for Promise state change (the process is irreversible)
    • From pending(in progress) to fulfilled(successful)
    • Change from pending(in progress) to rejected(failed)
  • important point
    • When the Promise object is created, the asynchronous inside will be executed immediately
    • Do not process asynchronous results when creating a promise, you should call resolve() or reject() to the then() method for processing
    • Promise solves the callback hell: return the next promise instance object in the then method of the previous promise.
      Requirements: read the four files abcd in turn
const fs = require('fs');

//Promise是一个构造函数,用于创建promise实例

//(1)调用Promise构造函数,生成promise实例对象
/* 
参数:回调函数  (resolve,reject)=>{  //你想要的异步操作 }
    resolve : 完成回调
    reject  : 失败回调 
*/
let p1 = new Promise((resolve, reject) => {
    
    

    //异步操作: 读取文件a
    fs.readFile(`${
      
      __dirname}/data/a.txt`, 'utf8', (err, data) => {
    
    
        if (!err) {
    
    //成功
            /* 
            (1)resolve:执行then方法里面的第一个函数
            (2)resolve底层原理:修改promise状态从pending(进行中)变为fulfilled(成功)
            */
            resolve(data);
        } else {
    
    //失败
            /* 
            (1)reject:执行then方法里面的第二个函数
            (2)rreject底层原理:修改promise状态从pending(进行中)变为rejected(失败)
            */
            reject(err);
        }
    });
});

let p2 = new Promise((resolve, reject) => {
    
    
    //异步操作: 读取文件a
    fs.readFile(`${
      
      __dirname}/data/b.txt`, 'utf8', (err, data) => {
    
    
        if (!err) {
    
    //成功
            resolve(data);

        } else {
    
    //失败
            reject(err);
        }
    });
});

let p3 = new Promise((resolve, reject) => {
    
    
    //异步操作: 读取文件a
    fs.readFile(`${
      
      __dirname}/data/c.txt`, 'utf8', (err, data) => {
    
    
        if (!err) {
    
    //成功
            resolve(data);

        } else {
    
    //失败
            reject(err);
        }
    });
});

let p4 = new Promise((resolve, reject) => {
    
    
    //异步操作: 读取文件a
    fs.readFile(`${
      
      __dirname}/data/d.txt`, 'utf8', (err, data) => {
    
    
        if (!err) {
    
    //成功
            resolve(data);

        } else {
    
    //失败
            reject(err);
        }
    });
});

//(2)调用promise实例的then方法

//第一个参数: 成功的回调
//第二个参数: 失败的回调
p1.then(data=>{
    
    
    console.log(data);
    return p2;//在第一个promise的then方法中返回第二个promise对象
})
.then(data=>{
    
    //p2的then
    console.log(data);
    return p3;
})
.then(data=>{
    
    //p3的then
    console.log(data);
    return p4; 
})
.then(data=>{
    
    //p4的then
    console.log(data);
});
  • The essence of promise is not to modify the order of asynchronous (asynchrony is always out of order), but to achieve orderly execution of asynchronous code by controlling the order of asynchronous results.

Promise method

  • catch() : catch the error err in the then method
  • all() : Put multiple Promise objects into an array and merge them into one promise
    • Then() will not be executed until all promises are executed: logical and
  • race() : Put multiple promise objects into an array and merge them into one promise
    • race: After any promise is executed, it will execute then(): logical OR
/* 需求 : 依次读取abcd四个文件
*/

const fs = require('fs');

//Promise是一个构造函数,用于创建promise实例

//封装一个创建promise的函数
function createPromise(filename){
    
    
    return new Promise((resolve,reject)=>{
    
    
        fs.readFile(`${
      
      __dirname}/data/${
      
      filename}.txt`, 'utf8', (err, data) => {
    
    
            if (!err) {
    
    //成功
                resolve(data);
    
            } else {
    
    //失败
                reject(err);
            }
        });
    });
};

let p1 = createPromise('a');
let p2 = createPromise('b');
let p3 = createPromise('c');
let p4 = createPromise('d');


//(2)调用promise实例的then方法
//第一个参数: 成功的回调
//第二个参数: 失败的回调
p1.then(data=>{
    
    
    console.log(data);
    return p2;//在第一个promise的then方法中返回第二个promise对象
})
.then(data=>{
    
    //p2的then
    console.log(data);
    return p3;
})
.then(data=>{
    
    //p3的then
    console.log(data);
    return p4; 
})
.then(data=>{
    
    //p4的then
    console.log(data);
})
.catch(err=>{
    
    
    //catch : 上面任何一个then出错了都会进入这个方法
    console.log(err); 
});

//all()方法
//Promise.all([p1,p2,p3,p4]) : 多个promise合成一个
let pAll = Promise.all([p1,p2,p3,p4]);

//(2)调用promise实例的then方法

pAll.then(data=>{
    
    
    //执行时机: pAll中所有的promise全部都完成才会执行then
    //data : 数组。 数组中每一个元素就是每一个promise的结果
    console.log(data);
    
});

//race方法

```js
//Promise.all([p1,p2,p3,p4]) : 多个promise合成一个
let pAll = Promise.race([p1,p2,p3,p4]);

//(2)调用promise实例的then方法

pAll.then(data=>{
    
    
    //执行时机: pAll中 任何一个 promise完成就会执行then
    //data : 第一个执行完毕的promise的结果
    console.log(data);
    
});

Array dimensionality reduction

Array dimensionality reduction is to turn a two-dimensional array into a one-dimensional array

Method 1 : concat() concatenation array of array

	/* 
        二维数组 : 数组每一个元素都是一个数组
        */
			let arr = [
				['a', 'b', 'c'],
				['d', 'e', 'f'],
				['g', 'h', 'i'],
			];

			console.log(arr);

			// 降维;
			//方式一:数组的concat()拼接数组
			let newArr = [];
			for (let i = 0; i < arr.length; i++) {
    
    
				newArr = newArr.concat(arr[i]);
			}
			console.log(newArr);

Method 2 : ES6 extended operator

二维数组 : 数组每一个元素都是一个数组
        */
			let arr = [
				['a', 'b', 'c'],
				['d', 'e', 'f'],
				['g', 'h', 'i'],
			];

            console.log(arr);
            
			//方式二:使用ES6的拓展运算符 ...
			let newArr = [];
			for (let i = 0; i < arr.length; i++) {
    
    
				newArr.push(...arr[i]);
			}
            console.log(newArr);

Array upgrade

One-dimensional array generates two-dimensional gainer multi-dimensional

  • Use the characteristics of the object to achieve array deduplication.
    Object characteristics
    obj.name Value : Yes : No value: undefined
    obj.name = 1 Assignment : Yes : Modify without: The property name of the dynamically added
    object cannot be repeated
	let arr1 = [88, 20, 66, 50, 90, 88, 20, 66];
			let obj = {
    
    }; //利用属性名不能重复特点实现数组去重

			let newArr = [];
			for (let i = 0; i < arr1.length; i++) {
    
    
				if (!obj[arr1[i]]) {
    
    //!undefined=true  obj.name 取值 :  有:取值  没有:undefined
					obj[arr1[i]] = 1; // obj.name = 1  赋值 : 有:修改  没有:动态添加
					newArr.push(arr1[i]);
				}
			}
			console.log(newArr);

One-dimensional array before dimension
Insert picture description here
upgrade Array after dimension upgrade

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44757417/article/details/108524593