Promise简记

Promise

"回调地狱"

function d() {
	console.log("hi")
}

d(function() {
	console.log(2)
	
	d(function() {
		console.log(3)
		
		d(function(){
			console.log(5)
			......
		}
	}
})

 <script>
        let btn = document.querySelector("button")
        let box = document.querySelector("div")
    
        btn.addEventListener('click', e=> {
            moveTo(box,100,100).then(()=>{
                console.log("第一次移动")
                return moveTo(box,200,200)
            }).then(()=> {
                console.log("第二次移动")
                return moveTo(box,300,300)
            }).then(()=> {
                console.log("第三次移动")
                return moveTo(box,400,400)
            })
        })
        
        function moveTo(el,x,y){
            return new Promise((res)=> {
                el.style.transform = `translate(${x}px,${y}px)`
                setTimeout(function(){
                    res()
                    box.textContent = `我移动了${x}px`
                },1000)
            
            })}
    // 小方块的移动
    
// promise实现图片的加载

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Promise</title>
    <style>
        div {
            width:180px;
            height: 180px;
            background: burlywood;
            transition: all 1s;
            text-align: center;
            font-size: 38px;
        }
        .wrap {
            transition: all 1s;
            width:100%;
            height:200px;
            background: #444;
        }
        img {
            float: left;
            height: 200px;
            width: 31%;
        }
    </style>
</head>
<body>
    <!-- <div></div>
    <button>点击</button> -->
    <div class="wrap"></div>
	<script>
        let URL = ['http://climg.mukewang.com/5b16558d00011ed506000338.jpg',
              'http://climg.mukewang.com/5b165603000146ca06000338.jpg ',
              'http://climg.mukewang.com/5b1656140001c89906000338.jpg' ]

        let i = 0
        function loadImg(URL) {
            return new Promise((res,rej) => {
                if(i<=3) {
                    setTimeout(()=>{
                        res(URL[i++]) 
                    },1000)
                } else {
                    console.log("停止!")
                }
            })
        }

        let wrap = document.querySelector(".wrap")
        loadImg(URL).then(function (url) {
            let img = document.createElement("img")
            img.src = url
            wrap.appendChild(img)
            return loadImg(URL)
        }).then(function (url) {
            let img = document.createElement("img")
            img.src = url
            wrap.appendChild(img)
            return loadImg(URL)
        }).then(function (url) {
            let img = document.createElement("img")
            img.src = url
            wrap.appendChild(img)
        })
        .catch(e => {
            console.log(e)
        })

	</script>
</body>
</html>

链式调用

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script type="text/javascript">
    
    
    function cook() {
        console.log('开始做饭。');
        var p = new Promise(function(resolve, reject){ 
            setTimeout(function() {
                console.log('做饭完毕!');
                resolve('鸡蛋炒饭');
            }, 1000);
        });
        return p;
    }
    
    function eat(data) {
        console.log('开始吃饭:' + data);
        var p = new Promise(function(resolve, reject) {
            setTimeout(function() {
                console.log('吃饭完毕!');
                resolve('一块碗和一双筷子');
            }, 2000);
        });
        return p;
    }
    function wash(data) {
        console.log('开始洗碗:' + data);
        var p = new Promise(function(resolve, reject) { 
            setTimeout(function() {
                console.log('洗碗完毕!');
                resolve('干净的碗筷');
            }, 2000);
        });
        return p;
}
    cook().then((e)=>{
        return eat(e)
    }).then((e)=>{
        console.log(e)
        return wash(e)
    })

</script>
</body>
</html>

1561018541974

错误处理

function cb(value) {
	return new Promise((res,rej)){
			if(value) resolve(value)
			else reject(value)
		}
}

cb(false).then(res=>console.log(res),rej=>console.log(rej))

.then(resolve,reject)两个处理函数

.catch(e => { console.log(e)}) 捕获未作处理的错误!

.finaly(e => {console.log(e)}) 最终肯定会被执行的步!

Promise的三种状态

  • pending
  • fulfilled
  • rejected

Promise.all()

Promise.all([promise1,promise2,promise3])

当里面的promise的实例全部成功时返回对应参数,有一个失败会返回对应的失败参数

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
}); 

Promise.all([p1, p2, p3]).then(values => { 
  console.log(values); // [3, 1337, "foo"] 
});

是空数组时会直接返回成功!

Promise.race()

Promise.race(iterable) 方法返回一个 promise,一旦迭代器中的某个promise解决或拒绝,返回的 promise就会解决或拒绝。(谁先解决或者失败则结束返回先处理完的值)

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
});

var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value);
  //都是resolve,但是promise2速度快!
});
// 最终输出: "two"

空数组不会被处理!

Promise.resolve()

Promise.reject()

Promise.resolve(value)方法返回一个以给定值解析后的Promise 对象。但如果这个值是个thenable(即带有then方法),返回的promise会“跟随”这个thenable的对象,采用它的最终状态(指resolved/rejected/pending/settled);如果传入的value本身就是promise对象,则该对象作为Promise.resolve方法的返回值返回;否则以该值为成功状态返回promise对象。

(包裹后会返回一个Promise对象)

  • 将同步任务通过Promise转换为异步任务!
function createAsyncTask(syncTask){
	return Promise.resolve(syncTask).then(syncTask => syncTask())
}

createAsyncTask(()=> {
	console.log("异步任务")
	return 1+1
}).then(res=>{
	console.log(res)
})

console.log("同步任务")
  • 习题(页面中有个板块,需要多张图片加载后才能显示)

    
    

Array.map()

posted on 2019-06-20 19:38  2481  阅读(152)  评论(0编辑  收藏  举报

导航