Promise的几个代码片段

片段1

<script>
        var p1 = new Promise(function(resolve, reject) {
            resolve(1)
        })

        var p2 = Promise.reject(2)

        // 异步1
        p2.then(function(value) {
            console.log('doo1')
        }, reason => {
            setTimeout(function() {
                 console.log('doo111111111111111') // [最后]
            }, 2000)

            console.log('doo11') // [1]

        }).then(value => {
            console.log('doo1111') // [4]
        }, value => {
            console.log('doo111')
        }).then(value => {
            console.log('doo11111') // [6]
        }, value => {
            console.log('doo111111')
        })

        // 异步2
        p2.catch(function(reason) {
            console.log('catch()' + reason) // [2]
            // return Promise.reject()
        }).then(value => {
            console.log('doo0') // [5]
        }, value => {
            console.log('doo00')
        })


        // 异步3
        p2.then(function(value) {
            console.log('doo2')
        }, reason => {
            console.log('doo22') // [3]
        })


        // Promise.all([p1, p2]).then(function(value) {
        //     console.log('onResolved()' + value)
        // }, function(reason) {
        //     console.log('onRejected()' + reason)
        // })
    </script>

异步1 异步2 异步3这个3组链式调用,是并行调用的,彼此之间不关联。

片段2

 <script>
        var p1 = new Promise(function(resolve, reject) {
            resolve('Rick')
        })

        setTimeout(() => {
            p1.then(value => {
                console.log('hello: ' + value) // 后指定回调函数
            })
        }, 1000)
    </script>

可以在resolve之后,再声明then

片段3

 <script>
        console.log('-----------')

        var p = Promise.reject(100)

        p.then(value => {}, reason => {
            console.log('---onRejected: ' + reason)
        }).catch(error => {
            console.log('---catch: ' + error) // 被then中的onRejected处理,catch就不会再执行
        })

        p.then(value => {}).catch(error => {
            console.log('---22222222catch: ' + error) // catch会再执行
        })

    </script>

如果在then中的oneRejected中处理了,就不会在catch中处理了。处理后,不抛出异常或rejected,下一个then将会执行onResolved

ES this的问题

浏览器环境

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this</title>
</head>
<body>
    <script>
        var age = 100
        var rick = {
            age: 30,
            name: 'Rick',
            grow() {
                console.log(`I am ${this.name}, I am ${this.age}`) // age: 30
                setTimeout(function() {
                    console.log(`I am ${this.age}`) // 100
                    console.log(`I am ${window.age}`) // 100
                    console.log(`I am ${age}`) // 100
                    console.log(window === this) // true
                }, 100)

            }
        }

        rick.grow()

        function testThis(param) {
            console.log(param + '. this === window => ' +  (this === window))
        }

        testThis(1) // 作为一个函数的话 this指向global,浏览器环境下就是window
        new testThis(2) // 作为一个对象的话 this指向对象

    </script>
</body>
</html>

node环境

// let age = 100;
age = 100

let rick = {
    age: 30,
    name: 'Rick',
    grow() {
        // console.log(`I am ${this.name}, I am ${this.age}`) // age: 30
        setTimeout(function() {
            console.log(`I am ${this.age}`) // 使用bind(this) age: 30. 否则this函数自身的this
            // console.log(this)

            // for (let k in this) {
            //     console.log(k)
            // }
        }.bind(this), 1001)

    }
}

// rick.grow()

// 数组复制
let a = [1, 2]
let b = [...a]
console.log(b)

// 对象复制
let user = {
    name: 'Jame'
}

let c = Object.assign({}, user) 
console.log(c)
let d = {...user}
console.log(d)

// 数组转函数参数
function test(a, b) {
    console.log(`a: ${a}, b: ${b}`)
    console.log(`2.this => ${this}`)
}
console.log(test(...a))
console.log(test.apply(null, a)) // apply的作用

console.log(`1.this => ${this}`)

history.pushState的用处

以前做后台管理的时候,采用的是ajax+iframe,导致的问题是“刷新”就会回到首页,采用html5的history.pushState可以更好的完成,项目pajx就是封装了history和ajax的功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <button id="btn">click</button>

    <a id="a" href="http://www.baidu.com" target="_self">baidu</a>

    <script>
        document.getElementById('btn').onclick = function() {
            var title = '新的页面'
            history.pushState(null, null, "line.html");

            document.title = title

            return false;
        }

        document.getElementById('a').onclick =  function () {
            console.log('...jump')

            // 可以阻止链接跳转
            return false
        }
    </script>
</body>
</html>

https://www.zhangxinxu.com/wordpress/2013/06/html5-history-api-pushstate-replacestate-ajax/

java8 Lambda&Stream Code

 /**
     * 获取年龄是22岁的员工
     */
    @Test
    public void testFilter() {
       list.stream()
               .filter(employee -> employee.getAge() == 22)
               .forEach(System.out::println);
    }

    /**
     *  获取所有员工的姓名,并用","连接
     */
    @Test
    public void testMap() {
        String str = list.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(","));
        System.out.println(str);
    }

    /**
     * 按照工资倒序排列,并获取第一个
     */
    @Test
    public void testSort() {
        Optional<Employee> optional = list.stream().sorted((e1, e2) -> {
            if (e1.getSlary() > e2.getSlary()) {
                return -1;
            } else if (e1.getSlary() == e2.getSlary()) {
                return 0;
            } else {
                return 1;
            }
        }).findFirst();

        System.out.println(optional.get());
    }

    /**
     * 最少工资
     */
    @Test
    public void testMin() {
        Double slary = list.stream()
                .map(Employee::getSlary)
                .min(Double::compareTo)
                .get();

        System.out.println(slary);
    }

    /**
     * 根据年龄进行分组
     */
    @Test
    public void testGroup() {
        Map<Integer, List<Employee>> map = list.stream().collect(Collectors.groupingBy(Employee::getAge));
        System.out.println(map);
    }

    /**
     * 工资大于5000的个数
     */
    @Test
    public void testCount() {
        Long count = list.stream().filter(employee -> employee.getSlary() > 8000)
                .count();

        System.out.println(count);
    }

    @Test
    public void testA() {

        BiPredicate<String, String> predicate2 = (s1, s2) -> s1.equals(s2);

        BiPredicate<String, String> predicate = String::equals;
        BiConsumer<List, String> bf = List::add;
        Function<Employee, String> f = Employee::getName;
        Supplier<String> s = String::new;

    }

    /**
     * 总薪水
     */
    @Test
    public void testStatistic() {
        DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Employee::getSlary));
        System.out.println(statistics.getSum());
    }

scss语法代码片段

/* Welcome to Compass.
 * In this file you should write your main styles. (or centralize your imports)
 * Import this file using the following HTML or equivalent:
 * <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" /> */

@import "variable"; //导入变量文件

// 需要安装插件 gem install compass-normalize
// config.rb配置 require 'compass-normalize'
@import "normalize" ; 
//@import "compass/reset";
@import "compass/layout";

@include sticky-footer(54px);

/**
`commonProperty`先声明再使用
*/
@mixin commonProperty($w: 50%) {
    background: #fff;
    padding: 5px;
    width: $w;
    float: left;
}

.btn { // 编译「显示」到css中
    margin: 0;
}


%btn-hidden { // 编译「不显示」到css中
    text-align: center;
}

//----
.btn-primary {
    @extend .btn;
    @extend %btn-hidden;
    @include commonProperty();
    padding: 9px;
}

html, body {
    color: $color;

    font: { // 属性嵌套
        family: '黑体';
        size: 16px;
    }

    @at-root { // 保留层次关系,编译后到顶层
        .header {
            position: relative;
        }
    }
}

p {
    @include commonProperty(100%);

    background-image: image-url("a.png"); //属性中,直接调用函数
}

@debug append-url("hello.png"); 

/**
`makecText`先声明再使用
*/
@function makeText($selector) {
    @return $selector;
}


#{ makeText(".hello-world") } { //如果在选择器材中使用,#{functionName}
    color: red;
    font-size: 20px;
}