手撕Promise和Async await原理

Promise原理:

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise { 
    status = PENDING; // 状态一经改变就不可变
    value = null;
    reason = null;
    successCallback = null;
    failCallback = null;

    constructor(executor) {
        this.resolve = this.resolve.bind(this);
        executor(this.resolve, this.reject)
    }
    resolve(value) {
        if (this.status !== PENDING) return;
        this.status = FULFILLED;
        this.value = value;
        this.successCallback && this.successCallback(this.value);
    }
    reject = reason => {
        if (this.status !== PENDING) return;
        this.status = REJECTED;
        this.reason = reason;
        this.failCallback && this.failCallback(this.reason);
    }
    then(successCallback, failCallback) {
        if (this.status === FULFILLED) {
            successCallback(this.value);
        } else if (this.status === REJECTED) {
            failCallback(this.reason);
        } else {
            // 等待状态 把两个函数存起来 更改状态之后才能执行then方法
            this.successCallback = successCallback;
            this.failCallback = failCallback;
        }
    }
}

module.exports = MyPromise;

Async await原理:

function myAjax1() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('成功111');
        }, 1000);
    });
}

function myAjax2() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('成功222');
        }, 1000);
    });
}

function* fun() {
    const myAjaxRes1 = yield myAjax1();
    console.log(myAjaxRes1, 'myAjaxRes1');
    const myAjaxRes2 = yield myAjax2();
    console.log(myAjaxRes2, 'myAjaxRes2');
}
const f = fun();
// const fNext = f.next();
// console.log(fNext);
// fNext.value.then(res => {
//     const fNext = f.next(res);
//     fNext.value.then(res => {
//         f.next(res);
//     })
// })

function handle(res) {
    if (res.done) return;
    res.value.then(data => {
        handle(f.next(data));
    })
}
handle(f.next());

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值