<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
let a = 1
let b = 2
let promise = new Promise(function(resolve, reject){ //规定就TM这么写
if(a==1) {
resolve(b)
}
})
// 上面等于下面这个
// let promise2 = Promise.resolve(2)
promise.then(success => console.log(success)).catch(err => console.log(err)) //2
//成功了就then, 失败就catch.
//.then 里面可以接收一个或者两个函数,成功(resolve)了走第一个函数,失败(reject)了走第二个函数
promise.then(success => {console.log(success);return success}).then(success => console.log(success)) //2 2
let p2 = promise.then(success => {console.log(success)}) //2
console.log(p2) //Promise {<pending>} 这个会最先返回,因为上面的都是异步
p2.then(success => console.log(success)) //undefined 因为上一步并没有return任何值过来
let p3 = promise.then(success => {console.log(success);return success}) //2
console.log(p3) //Promise {<pending>} 第二个返回
console.log(promise) //Promise {<resolved>: 2} 第三个返回
//promise有三种状态:pending/reslove/reject 。pending就是未决,resolve可以理解为成功,reject可以理解为拒绝。
//Promise.all的使用。都成功了走then,失败了catch
let a1 = Promise.resolve("aaa")
let a2 = Promise.resolve("bbb")
let a3 = Promise.resolve("ccc")
let a4 = Promise.reject("ddd")
Promise.all([a1,a2,a3]).then(res=>console.log(res)).catch(err=>console.log(err)) //["aaa","bbb","ccc"]
Promise.all([a1,a2,a3,a4]).then(res=>console.log(res)).catch(err=>console.log(err)) //ddd
</script>
</body>
</html>
Promise的使用
最新推荐文章于 2022-07-05 11:17:55 发布