异步编程-订单模式

//0:在排队 1:处理中 2 订单完成 3 订单取消 4 超时处理
const ShopOrderMap={}
class Order {
    constructor(name){
        this.name=name||'test';
        if(!ShopOrderMap[name]){
            ShopOrderMap[name]={
                bit:[],
                curN:0,
                orderMap:{}//待处理的订单
            };
        }
        this.shopOrder=ShopOrderMap[this.name];
        //新增加一个订单
        this.myN=this.shopOrder.bit.length;
        this.shopOrder.bit[this.myN]='0';
        this.shopOrder.orderMap[this.myN]=this;

    }
    //排队
    wait(overTime){

        return new Promise((res)=> {
            this.res=res;
            //没有人排队,处理当前订单
            this.resolve()
        })
        if(overTime){
            this.timeInter=setTimeout(()=>{
                this.reject()
            },overTime)
        }
    }
    //排队处理订单
    resolve(){
        if(this.myN===this.shopOrder.curN){
            if(this.shopOrder.bit[this.myN]==='0'){
                this.shopOrder.bit[this.myN]='1';
                if(this.res){
                    this.res({flag:'S'})
                }
                delete this.res;
                delete this.shopOrder.orderMap[this.myN];
            }else if(this.shopOrder.bit[this.myN]!=='1'){
                this.end()
            }
        }

    }
    //处理当前订单
    reject(){
        if(this.shopOrder.bit[this.myN]==='0'){
            this.shopOrder.bit[this.myN]='4';
            if(this.res){
                this.res({
                    flag:'F',msg:'任务超时'
                })
            }
            this.end()
        }
    }
    //激活一个订单
    active(){
        if(this.myN>this.shopOrder.curN&&this.shopOrder.bit[this.myN]==='3'){//取消一个订单
            this.shopOrder.bit[this.myN]='0';
        }
    }
    //取消一个订单
    end(){
        if(this.timeInter){
            clearTimeout(this.timeInter);
            this.timeInter=null;
        }
        if(this.myN===this.shopOrder.curN){
            if(this.shopOrder.bit[this.myN]==='1'){
                this.shopOrder.bit[this.myN]='2';
            }
            this.shopOrder.curN++
            if(this.shopOrder.curN<this.shopOrder.bit.length){
                this.shopOrder.orderMap[this.shopOrder.curN].resolve();
            }

        }else if(this.myN>this.shopOrder.curN&&this.shopOrder.bit[this.myN]==='0'){//取消一个订单
            this.shopOrder.bit[this.myN]='3';
        }
    }

}


function sleep(time) {
    return new Promise((res)=>{
        setTimeout(res,time)
    })
}
async function init() {
    //生成一个订单
    const order=new Order('test')
    const res=await order.wait();//等待其他订单处理完成
    await sleep(1000)
    console.log('order1',res)

    order.end()
}
async function init2() {
    //生成一个订单
    const order=new Order('test')
    const res=await order.wait(8000);//等待其他订单处理完成
    console.log('order2',res)

    order.end()
}
init()
init2()

猜你喜欢

转载自www.cnblogs.com/caoke/p/11876850.html