1.Promise的三种状态
- Pending----Promise工具实例建设时辰的初始状态
- Fulfilled----可以领略为乐成的状态
- Rejected----可以领略为失败的状态

这个理睬一旦从守候状态酿成为其他状态就永久不能变动状态了,好比说一旦状态变为 resolved 后,就不能再次改变为Fulfilled
- let p = new Promise((resolve, reject) => {
- reject('reject')
- resolve('success')//无效代码不会执行
- })
- p.then(
- value => {
- console.log(value)
- },
- reason => {
- console.log(reason)//reject
- }
- )
当我们在结构 Promise 的时辰,结构函数内部的代码是当即执行的
- new Promise((resolve, reject) => {
- console.log('new Promise')
- resolve('success')
- })
- console.log('end')
- // new Promise => end
2.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)
- return 2 //包装成 Promise.resolve(2)
- })
- .catch(err => 3)
- .then(res => console.log(res))
- // 例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)
- // 例3
- let fs = require('fs')
- function read(url) {
- return new Promise((resolve, reject) => {
- fs.readFile(url, 'utf8', (err, data) => {
- if (err) reject(err)
- resolve(data)
- })
- })
- }
- read('./name.txt')
- .then(function(data) {
- throw new Error() //then中呈现非常,会走下一个then的失败回调
- }) //因为下一个then没有失败回调,就会继承往下找,假如都没有,就会被catch捕捉到
- .then(function(data) {
- console.log('data')
- })
- .then()
- .then(null, function(err) {
- console.log('then', err)// then error
- })
- .catch(function(err) {
- console.log('error')
- })
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|