| 
                         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')  
 -   }) 
 
                          (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |