Loading... #### 1.promise本身是同步的,只有.then .catch是异步的 所以使用时记得把它封装到一个函数里 #### #### 2.promise 有 3 种状态:pending、fulfilled 或 rejected。状态改变只能是 pending->fulfilled 或者 pending->rejected,状态一旦改变则不能再变。 #### const promise = new Promise((resolve, reject) => { resolve('success1') reject('error') resolve('success2') }) promise.then((res) => { console.log('then: ', res) }) .catch((err) => { console.log('catch: ', err) }) //结果为then:success1 #### 3.promise 可以链式调用。promise 每次调用 .then 或者 .catch 都会返回一个新的 promise,从而实现了链式调用 #### Promise.resolve(1) .then((res) => { console.log(res) return 2 }) .catch((err) => { return 3 }) .then((res) => { console.log(res) }) //结果为1 2 #### 4. .then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获,需要改成其中一种: #### return Promise.reject(new Error('error!!!')) throw new Error('error!!!') #### 5. .then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环。类似于: #### process.nextTick(function tick () { console.log('tick') process.nextTick(tick) }) #### 6..then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。 #### Promise.resolve(1) .then(2) .then(Promise.resolve(3)) .then(console.log) //结果为1 END 最后修改:2021 年 09 月 08 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果觉得我的文章对你有用,请随意赞赏 下一篇 上一篇 发表评论 取消回复 使用cookie技术保留您的个人信息以便您下次快速评论,继续评论表示您已同意该条款 评论 * 私密评论 名称 * 🎲 邮箱 * 地址 发表评论 提交中...