基本使用
promise是一种构造函数,本身有三种状态:
pedding(等待态)
resolved(成功态)
rejected(失败态)
成功与失败互斥
默认是等待态
创建简单的peomise对象
// 创建一个promise对象
// 参数是一个函数, 有两个0形参resolve, reject
// 该执行函数会立即执行
const p1 = new Promise(function (resolve, reject) {
// executor执行函数代码出现异常, 直接走失败
// 任务
console.log(123);
// resolve('有钱')
reject('没钱啊')
})
//then接受两个参数
// 第一个参数是成功的回调函数
// 第二个参数是失败的回调函数
p1.then(
(data) => {
console.log('success', data);
},
(reason) => {
console.log('error', reason);
}
)
</script>
其他静态方法
Promise.resolve('成功').then((data) => {
console.log(data);
})
new Promise((resolve, reject) => {
resolve('成功')
}).then((data) => {
console.log(data);
})
let p = new Promise((resolve, reject) => {
reject('错误')
})
p.then(
(data) => {
console.log(data);
},
(reason) => {
console.log(resson);
}
)
p.then((data) => {
console.log(data);
}).catch(function (r) {
console.log(r);
})
catch是then的语法糖
模拟封装promise
<script>
function Promise(executor) {
const resolve = (data) => {
if (this.status === 'pedding') {
this.status = '成功'
this.data = data
this.onFullfilledabc.forEach((item) => item(this.data))
}
}
const reject = (reason) => {
if (this.status = 'pedding') {
this.status = '失败'
this.data = reason
this.onRejectedabc.forEach((item) => item(this.data))
}
}
this.status = 'pedding'
this.data = ''
this.onFullfilledabc = []
this.onRejectedabc = []
try {
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
Promise.prototype.then = function (onFullfilled, onRejected) {
if (this.status = '成功') {
onFullfilled(this.data)
}
if (this.status === '失败') {
onRejected && onRejected(this.data)
}
if (this.status === 'pedding') {
this.onFullfilledabc.push(onFullfilled)
this.onRejectedabc.puah(onRejected)
}
}
const pp = new Promise((resolve, reject) => {
resolve('hhh')
})
console.log(pp.status, pp.data);
</script>
链式调用
<script>
function getJSON(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('get', url)
xhr.responseType = 'json'
xhr.setRequestHeader('Accept', 'application/json')
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
resolve(xhr.response)
}
}
xhr.send()
})
}
const p = getJSON('http://localhost:8899/goodsList')
p.then(
(data) => {
console.log('第一次请求结果', data);
// 再次发请求
// 这里return的返回值决定下一次then的成功还是失败
// return 是普通值直接走下次成功
// return 是promise, promise是成功下次then走成功 promise是失败下次then走失败
return getJSON('http://localhost:8899/cart')
// return 100
// return promise((resolve, rejext) => {
// rejext('出错了')
// })
}, (reason) => {
console.log(reason);
}
)
.then(
(data) => {
console.log('第二次请求结果', data);
},
(err) => {
console.log(r);
}
)
</script>