1.Promise的三种状态,一旦改变就无法再变更了,比如一旦变为 resolved 后,就不能再次改变为Fulfilled
例如:
let p = new Promise((resolve, reject) => {
reject('reject')
resolve('success')//无效代码不会执行
})
p.then(
value => {
console.log(value)
},
err => {
console.log(err)//reject
}
)
2.构造 Promise 的时候,构造函数内部的代码是立即执行的
new Promise((resolve, reject) => {
console.log('new Promise')
resolve('success')
})
console.log('end')
// new Promise => end
3.promise的链式调用
每次调用返回的都是一个新的Promise实例(这就是then可用链式调用的原因)
如果then中返回的是一个结果的话会把这个结果传递下一次then中的成功回调
如果then中出现异常,会走下一个then的失败回调
在 then中使用了return,那么 return 的值会被Promise.resolve() 包装(见例1,2)
then中可以不传递参数,如果不传递会透到下一个then中(见例3)
catch 会捕获到没有捕获的异常
// 例1
Promise.resolve(1)
.then(res => {
console.log(res) //1
return 2 //包装成 Promise.resolve(2)
})
.catch(err => 3)
.then(res => console.log(res)) //2
// 例2
Promise.resolve(1)
.then(x => x + 1)
.then(x => {
throw new Error('My Error')
})
.catch(() => 1)
.then(x => x + 1)
.then(x => console.log(x)) //2
.catch(console.error)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。