<!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>Promise</title>
</head>
<body>
<script>
resolve == then,reject == catch
let promise = new Promise((resolve, reject) => {
reject(2222)
})
promise.then(response => {
console.log('成功')
console.log(response)
}).catch(error => {
console.log('失败')
console.log(error)
})
function promise1(status){
return new Promise((resolve, reject) => {
if(status) {
console.log('第1个promise成功');
resolve('第1个promise返回数据成功');
}
if(!status) {
console.log('第1个promise失败');
reject('第1个promise返回数据失败')
}
})
}
function promise2(status){
return new Promise((resolve, reject) => {
if(status) {
console.log('第2个promise成功');
resolve('第2个promise返回数据成功')
}
if(!status) {
console.log('第2个promise失败');
reject('第2个promise返回数据失败')
}
})
}
function promise3(status){
return new Promise((resolve, reject) => {
if(status) {
console.log('第3个promise成功');
resolve('第3个promise返回数据成功')
}
if(!status) {
console.log('第3个promise失败');
reject('第3个promise返回数据失败')
}
})
}
function promise4(status){
return new Promise((resolve, reject) => {
if(status) {
console.log('第4个promise成功');
resolve('第4个promise返回数据成功')
}
if(!status) {
console.log('第4个promise失败');
reject('第4个promise返回数据失败')
}
})
}
promise1(true)
.then(response => {
console.log(response)
return promise2(true)
})
.then(response => {
console.log(response)
return promise4(true)
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Promise.all([promise1(true), promise2(true), promise3(true)]).then(response => {
console.log('全部调用成功');
}).catch(error => {
console.log('有些可能失败了');
})
Promise.race([promise1(false), promise2(true), promise3(true)]).then(response => {
console.log('成功');
}).catch(error => {
console.log('失败了');
})
</script>
</body>
</html>