java 实现 Promise

java 实现 类js的 Promise

最近感觉js的Promise很神奇, 就想用JAVA实现一遍
废话不多说, 直接上代码

import java.util.ArrayList;
import java.util.List;

/**
 * Promise
 *
 * @author hengzi
 * @date 2022/8/11
 */
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public class Promise {

    public static final String PENDING = "PENDING";

    public static final String FULFILLED = "FULFILLED";

    public static final String REJECTED = "REJECTED";

	//Promise 的状态
    private String state = PENDING;
    
	//结果
    private Object value;


    //成功的回调
    private final List<Callback> onFulfilledList = new ArrayList<>();

    //失败的回调
    private final List<Callback> onRejectedList = new ArrayList<>();

    public Promise() {
        throw new RuntimeException();
    }

	// 定义一个回调函数--有返回值
    public interface Callback<R>{
        Object run(R r);
    }
    
    // 定义一个回调函数--无返回值
    public interface Function<R>{
        void run(R r);
    }

    
	// 定义一个执行函数
    public interface Executor<T> {
         void executor(Callback<T> resolve, Callback<T> reject);
    }


    public <R> Promise(Executor<R>  executor) {
            Callback<R> resolve = r -> {
                if(state.equals(PENDING)){
                    state = FULFILLED;
                    value = r;
                    onFulfilledList.forEach(fn->fn.run( value));
                }
                return null;
            };

        Callback<R> reject = r-> {
            if(state.equals(PENDING)){
                state = REJECTED;
                value = r;
                onRejectedList.forEach(fn->fn.run( value));
            }
            return null;
        };
        try {
            executor.executor(resolve,reject);
        }catch (Exception e){
            reject.run((R) e);
        }
    }

    public  <T> Promise then(Function<T> onFulfilled){
        return then(res->{
            onFulfilled.run((T) res);
            return null;
        },err->null);
    }

    public  <T> Promise then(Function<T> onFulfilled,Function<T> onRejected){
        return then(res->{
            onFulfilled.run((T) res);
            return null;
        },err->{
            onRejected.run((T) err);
            return null;
        });
    }

    public  <T> Promise then(Callback<T> onFulfilled){
        return then(onFulfilled,  t -> null);
    }

    /**
     * then 核心方法是then
     * @param onFulfilled 成功的回调函数
     * @param onRejected 失败的回调函数
     * @return Promise
     */
    public  <T> Promise then(Callback<T> onFulfilled, Callback<T> onRejected){

        Promise _this = this;
        return new Promise( (resolve, reject) -> {

            if(_this.state.equals(FULFILLED)){
                Object run = onFulfilled.run((T) value);
                resolvePromise(_this, run, resolve, reject);
            }
            if(_this.state.equals(REJECTED)){
                Object run =  onRejected.run((T) value);
                resolvePromise(_this, run, resolve, reject);
            }
            if(_this.state.equals(PENDING)){
                onFulfilledList.add(o -> {
                    Object run = onFulfilled.run((T) value);
                    resolvePromise(_this, run, resolve, reject);
                    return null;
                });
                onRejectedList.add(o -> {
                    Object run =  onRejected.run((T) value);
                    resolvePromise(_this, run, resolve, reject);
                    return null;
                });
            }
        });
    }


    public static <T> void resolvePromise(Promise promise2, T x, Callback<T> resolve, Callback<T> reject){

        if(promise2 == x ){
            // 如果 这两个是同一个对象 ,就会造成无限循环
            reject.run((T) new IllegalArgumentException("Chaining cycle"));
            return;
        }
        if(x instanceof Promise){
            // 如果它返回的是一个新的 Promise对象
            try {
                   ((Promise) x).then(
                           y->{
                               // 那么 等这个新的 Promise 执行完之后 再执行一遍这个 y 就是执行结果
                               resolvePromise(promise2, (T) y, resolve, reject);
                               return null;
                           },
                           r->{
                               reject.run((T) r);
                               return null;
                           });

            } catch(Exception e){
                reject.run((T) e);
            }
        }
        else {
            // 如果是其他东西,就返回这个结果
            resolve.run(x);
        }
    }

    public static <T> Promise all(Promise ...promiseList) {
    
        final int[] count = {0};
        List<T> res = new ArrayList<>();
        int length = promiseList.length;
        
        return new Promise((resolve, reject)->{
            for (Promise promiseTest : promiseList) {
                promiseTest.then(val -> {
                    count[0]++;
                    res.add((T) val);
                    if (count[0] == length) {
                        resolve.run(res);
                    }
                    return val;
                }, err->{
                    return reject.run(err);
                });
            }
        });
    }
}


这是个简易版, 未经严格测试, 仅供娱乐.

使用Promise

        // 一般情况下
        new Promise((resolve, reject) -> {
            System.out.println("4");
            resolve.run("5");
        }).then(res->{
            System.out.println("then.resolve.res="+res);
        },err->{
            System.out.println("then.reject.err="+err);
        });
        
        // 链式调用
	    new Promise((resolve, reject) -> {
            System.out.println("666");
            resolve.run("666");
        }).then(res->{
            System.out.println("then.res1="+res);
            return "null1";
        }).then(res->{
            System.out.println("then.res2="+res);
            return new Promise(((resolve2, reject) -> {
                resolve2.run("弟中弟");
            }));
        }).then(res->{
            System.out.println("then.res3="+res);
        });

  		// all调用
		Promise.all(
                new Promise((resolve, reject) -> {
                	// do something
                    resolve.run("?");
                }),
                new Promise(((resolve, reject) -> {
                    resolve.run("22reject");
                }))
        ).then(res->{
            System.out.println("all res="+res);
        },err->{
            System.out.println("all err="+err);
        });

声明一下, 写这东西只是为了更加了解接口编程, 未经严格测试, 可能是有bug的. 出现问题概不负责~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值