糙寫Promise

var a=new Promise(function(a,b){
    setTimeOut(a,5000);
})
setTimeOut(function(){
    a.then(()=>{
        console.log('5秒之後一定會執行')
    }
},5000);

console.log一定會在5秒後執行
Promise在實例化之後就進入了pending狀態,直到執行resolve方法,纔會將狀態改爲resolved,如果執行reject,則狀態改爲rejected

不管狀態發生怎麼改變,a這個Promise裏面的邏輯是肯定會全部執行完畢的


resolve方法和reject方法都是會在隊尾執行,這塊可以看polyfill,
resolve(){
setTimeOut(function(){
},0);
}

            var a=new Promise(function(a,b){
                    for(var i=0;i<5;i++){
                        if(i==3){
                            a();
                        }
                        console.log(2)
                    }
                    console.log(3)      
            })
            a.then(function(){
                console.log(4);
            })
            //依次輸出2 2 2 2 2 3 4
            //而不是 2 2 2 2 4 2 3
            var a=new Promise(function(a,b){
                    for(var i=0;i<10;i++){
                        if(i==9){
                            a();
                        }
                        console.log(2)
                    }
                    console.log(3)      
            })
            a.then(function(){
                console.log('a then執行');
            })
            var b=new Promise(function(a,reject){
                a();
                for(var i=0;i<10000;i++){
                    if(i==9999){
                        console.log(i);
                    }
                }
            })
            b.then(function(){
                console.log('b then執行')
            })

//這個應該輸出什麼呢


//2 2 2 2 2 2 2 2 2 2 3 9999 a then執行 b then執行

爲什麼上面會這麼輸出
是因爲同步計算永遠優先異步計算
a=new Promise和b=new Promise都是同步計算,所以裏面的輸出會優先 輸出,a.then和b.then都是異步計算,會被無限往後推,實現原理是setTimeOut(xxx,0);

            var a=new Promise(function(a,b){
                    for(var i=0;i<10;i++){
                        if(i==9){
                            a();
                        }
                        console.log(2)
                    }
                    console.log(3)      
            })
            a.then(function(){
                console.log('a then執行');
            })
            console.log('4');
            var b=new Promise(function(a,reject){
                a();
                for(var i=0;i<10000;i++){
                    if(i==9999){
                        console.log(i);
                    }
                }
            })
            b.then(function(){
                console.log('b then執行')
            })
            console.log('5');
            console.log('6');

//2 2 2 2 2 2 2 2 2 2 3 4 9999 5 6 a then執行 b then執行
//這就是根據上面的邏輯得出的輸出順序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章