细说promise-避免回调地狱(第一次写,未完待续)

93 阅读1分钟

一、await、promise出现的背景。

1)相同点:

1.解决异步操作问题。

2)不同点:

  • 1.await将几个异步操作,合并成同步请求。
  • 2.promise是最近才出现的解决异步调用的一种方案。它可以组成一链式调用,有效的防止了多层异步调用造成的嵌套地狱。

二、用法示例

async function awaitTest() {
    let res1 = await awaitCallA();
    //res1里的值会作为下面函数的参数
    //callQequest会等到awaitCallA异步函数返回后才执行,
    //在awaitCallA函数返回值前,awaitTest函数会被挂起,暂停执行。
    callQequest(res1.data);
}

function awaitCallA() {
    setTimeout(()=>{
        console.log();
    }, 1000);
}

三、await注意事项

四、promise注意事项

1.promise使用方法:

let promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            let num = Math.random();
            if(num >0.5) {
                resolve('ok');
            } else {
                reject('error');
            }
        }, 1000);
    });
附上Promise的代码实现
class MyPromise() {
    constructor(callback) {
        //promise正在请求状态
        this.pending = 'pending';
        //正确请求状态
        this.resolved = 'ok';
        //错误状态
        this.rejected = 'error';
        //初始状态为pending状态
        this.status = this.pending;
        //resolveList
        this.resolveList = [];
        this.rejectList= [];
        
        if(this.status === this.pending) {
            callback(resolve, reject);
        }
        //循环遍历成功list
        function resolve(res) {
            if(res instanceof MyPromise) {
                return res.then(resolve, reject);
            }
            if(this.state === this.pending) {
                this.status = this.resolved;
                this.resolveList.foreach((func, index) => {
                    if(typeof func === 'function') {
                        func(res);
                    }
                });
            }
        }
        //循环遍历失败list
        function reject(res) {
          if(this.status === this.pending) {
            this.status = this.rejected;
            this.status = this.rejected;
            this.rejectList.foreach((func, index) => {
                if(typeof func === 'function') {
                    func(res);
                }
            });
          }
        }
    }
    //promise的then函数,返回一个promise对象;
    then(resolve, reject) {
        return new MyPromise((resolve, reject) => {
            let resolveHandler = () => {
                let res = resolve();
                return res instanceof MyPromise ? res.then(resolve,reject) : resolve(res);
            }
            let rejectHandler = () => {
                let res = resolve();
                return res instanceof MyPromise ? res.then(resolve, reject) : reject(res);
            }
            
            if(this.status === this.pending) {
                this.resloveList.push(resolveHandler);
                this.rejectList.push(resolveHandler);
            } else if(this.status === this.resolved) {
                resolvedHandler();
            } else if(this.status === this.rejected) {
                rejectHandler();
            }
        });
    }
    
    //all方法,接受一个promise对象的数组
    all(promises) {
        return new MyPromise((resolve, reject) => {
            const maxCount = promises.length;
            let curCount = 0;
            const resList = [];
            for(let i=0;i < maxCount; i++) {
                Promise.resolve(promises[i]).then((res) => {
                    resList.push(res);
                    curCount++;
                    if(curCount >= maxCount) {
                        return resolve(resList);
                    }
                }, error => {
                    return reject(error);
                });
            }
        });
    }
}