react native tips

Demo


        console.log('aaaaa0');
        setTimeout(() => {
            console.log('aaaaa1');
        }, 0);

        console.log('aaaaa3');


        new Promise((resolve, reject) => {
            console.log('aaaaa4')
            resolve('aaaaa4');

            console.log('aaaaa5');
            resolve('aaaaa5');

            console.log('aaaaa6');
            reject('aaaaa6')

            console.log('aaaaa7');
            reject('aaaaa7')
            console.log('aaaaa7.0');
        }).then((result) => {
            console.log('aaaaa8');
            console.log(result);
            console.log('aaaaa9');
        }).catch(e => {
            console.log('aaaaa10');
            console.log(e);
            console.log('aaaaa11');
        });

        console.log('aaaaa12');
        this.setState({
            countryId: 2
        }, () => {
            console.log('aaaaa2', this.state.countryId);
        });
        this.setState({
            countryId: 3
        }, () => {
            console.log('aaaaa13', this.state.countryId);
        });
        console.log('aaaaa14');

上面输出结果为

aaaaa0
aaaaa3
aaaaa4
aaaaa5
aaaaa6
aaaaa7
aaaaa7.0
aaaaa12
aaaaa14
aaaaa2 3
aaaaa13 3
aaaaa8
aaaaa4
aaaaa9
aaaaa1

有兴趣的可以把上面的顺序打乱,再观察下执行顺序

出现上述的结果,可以暂时归纳为下面几个结果:

setTimeout是宏任务

promise 是微任务,当一个函数里有多个resole和reject, 第一个才会真正的生效;resole/reject 不等于return ,他们后面的代码还会执行;有promise的时候才会

setState是微任务,在微任务里最后才会执行,有promise出现的时候比then先执行;多个setState 会合并,同一个字段,后面的值会覆盖前面的;

微任务执行完毕后,才会执行宏任务;

posted @ 2019-11-01 18:45  shidaying  阅读(209)  评论(0编辑  收藏  举报