为了转生而点技能-JavaScript,day23(Promise介绍

Promise:适用於非同步的运算上。

  1. 本身就是建构函式
console.log(Promise);     //ƒ Promise() { [native code] }
  1. 利用chrome可以观测到Promise的状态,分为pendingfulfilledrejected状态不会同时存在
    搁置(pending):初始状态。
    实现(fulfilled):表示操作成功地完成,透过then() 来接续後续的动作。
    拒绝(rejected):表示操作失败了,透过catch() 来接续後续的动作。。
        const a = new Promise(function (resolve, reject) { });
        console.log(a);

https://ithelp.ithome.com.tw/upload/images/20211216/20143762cQYKymQNhB.jpg

fulfilled:

        const a = new Promise(function (resolve, reject) { return resolve('success') });
        console.log(a);                               //Promise {<fulfilled>: 'success'}
        a.then((param) => { console.log(param) });    //success,param只是用来接收fulfilled的

rejected:

        const a = new Promise(function (resolve, reject) { return reject('fail') });
        console.log(a);                               //Promise {<rejected>: 'fail'}
        a.catch((param) => { console.log(param) });   //fail,param只是用来接收rejected的
        const a = function promiseFn(num) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve('real');
                    }
                    else {
                        reject('empty');
                    }
                }, 10);
            })
        }
        a(1)
            .then((param) => console.log(param));   //real
            
            
            
            
            
        function promiseFn(num) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve('real');
                    }
                    else {
                        reject('empty');
                    }
                }, 10);
            })
        }
        promiseFn(0)
            .then((param) => console.log('sucess ' + param))
            .catch((param) => console.log('false ' + param) //false empty

.then.catch可以合并撰写,表示如下:

            promiseFn(0)
            .then((param) => { console.log('sucess ' + param) },
                  (param) => { console.log('false ' + param) }); //false empty


3.Promise chain:可以依序且依照不同结果,呼叫两个以上的非同步函数。

        function promiseFn(num) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {             //参数为真值时
                        resolve('real');
                    }
                    else {                 //参数为假值时
                        reject('empty');
                    }
                }, 10);
            })
        }
        
        
        promiseFn(0)                           //参数为假值,为reject状态
            .then((param) => {
                console.log('sucess ' + param)
                return promiseFn(1)
            },
                (param) => {                   //接收reject状态时的参数
                    console.log('false ' + param)
                    return promiseFn(2)        //回传参数2给PromiseFn判断,为真值,为fulfilled状态
                })
            .then((param) => {                 //接收fulfilled状态时的参数
                console.log('sucess ' + param)
                return promiseFn(0)            //回传参数0给PromiseFn判断
            },
                (param) => {
                    console.log('false ' + param)
                    return promiseFn(1)
                })
            .then((param) => {
                console.log('sucess ' + param)
            },
                (param) => {
                    console.log('false ' + param)
                })

入门级Promise用法:
1.Promise.all:会依据给定不同的时间点执行且执行结果为fulfilled後,并再传给.then统一执行後续;如果途中有任一结果为rejected,就会直接找.catch执行後续。

        function promiseFn(num, time = 500) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve(`real ${num}`);
                    }
                    else {
                        reject('empty');
                    }
                }, time);
            });
        }
        
        
        Promise.all([
            promiseFn(1, 1000),
            promiseFn(2, 2000),
            promiseFn(3, 3000),
        ])
            .then((param) => { console.log(param) })   //(3) ['real 1', 'real 2', 'real 3']
            .then((param) => { console.log(param[0], param[1], param[2])})//real 1 real 2 real 3

2.Promise.race:会依据给定不同的时间点执行且执行结果为fulfilled後,且只会将第一个执行完毕的结果传给.then後执行後续;如果有任一执行结果为rejected,则依照次序决定是否呈现fulfilled的後续结果或是呈现为rejected的後续结果。
皆为fulfilled

        function promiseFn(num, time = 500) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve(`real ${num}`);
                    }
                    else {
                        reject('empty');
                    }
                }, time);
            });
        }
        Promise.race([
            promiseFn(1, 1000),
            promiseFn(2, 20),
            promiseFn(3, 3000),
        ])
            .then((param) => { console.log(param) })    //real 2,因为只会呈现promiseFn(2, 20)

任一为rejected

        function promiseFn(num, time = 500) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve(`real ${num}`);
                    }
                    else {
                        reject('empty');
                    }
                }, time);
            });
        }
        Promise.race([
            promiseFn(0, 1000),
            promiseFn(2, 20),
            promiseFn(3, 3000),
        ])
            .then((param) => { console.log(param) })    //real 2,promiseFn(2, 20)次序最前
            .catch((param) => { console.log(param) })
        function promiseFn(num, time = 500) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    if (num) {
                        resolve(`real ${num}`);
                    }
                    else {
                        reject(`empty ${num}`);
                    }
                }, time);
            });
        }
        Promise.race([
            promiseFn(1, 1000),
            promiseFn(0, 20),
            promiseFn(3, 3000),
        ])
            .then((param) => { console.log(param) })
            .catch((param) => { console.log(param) })   //empty 0,因为promiseFn(0, 20)次序靠前

<<:  D5. 学习基础C、C++语言

>>:  LeetCode 6. Zigzag Conversion

Day29:PVE 更多未提及的技术

前言 来到倒数最後一天,我们来谈谈其他有关 PVE 的其他技术或可搭配的工具。 更多虚拟化的技术 S...

iOS APP 开发 OC 第七天, nil 跟 NULL 一样吗?

tags: OC 30 day NULL 可以作为指针变量的值。如果一个指针变量的值是NULL值,代...

第 8 天 迈出 RxJS 小小的一步|pipe、operators

前情提要 使用了 AsyncPipe 管道来取得所有英雄资料後,我们要在英雄资讯页面,传递参数来取得...

来讲讲 Cypher 的 Coding Style 吧

前情提要 除结尾倒数两篇 (゚∀゚) 来看看能不能在今天一次性写完w 现在时间 10/11 aka....

XSS&CSRF&Replay

跨站点脚本(Cross-Site Scripting:XSS)和注入(Injection) 输入验证...