Promise

作者: nCov | 来源:发表于2019-07-13 17:48 被阅读0次

es6 Promise resolve 成功 reject失败

new Promise((resolve, reject) => {
       
    })
let  that=this;

test.then(function(student){
    console.log('第一个学生')
    return that.student2()
}).then(function(student){
     console.log('第二个学生')
}).catch(function(err){
     console.log(err)
 // 处理前面Promise产生的错误
})

体验箭头符号写法,都是箭头符号可让代码变得简洁;

let  that=this;

test.then(student=>{
  console.log('第一个学生')
       return that.student2()
}).then(student=>{
      console.log('第二个学生')
}).catch(function(err){
    console.log(err)
 // 处理前面Promise产生的错误
})

每一次then都是新的promise对象,当第一个then 成功就会调用第二个then,如第一个就出现错误就调用catch,同理第二出现错误也调用 catch

抛出错误写法,这个也要了解下调试代码可用 throw

写法:

function test(){
  
 return  new Promise(function (resolve, reject) {
               throw new Error('悲剧了,又出 bug 了');
           }).catch(function(err){
                return err
           });
  
}

test()

return了一个Error,代码依然会按照正常的流程走下去,并不会执行后续的catch函数,
这个是不同于thorw抛出一个Error的,如果是throw抛出一个Error则会被catch函数,所以
我们可以这样写.


function test(){
 return  new Promise(function (resolve, reject) {
           return     reject('悲剧了,又出 bug 了');
           }).catch(function(err){
                throw  new Error(err)   
           });
  
}


有时候我们需要知道链式promise函数中,如何判断是哪个promise抛出的错误?

1 catch,根据promise抛出的特定错误码,区分到底是哪个promise抛出的错误

2 在每一个then方法的第二个参数函数里输出错误信息

function test(){
return new Promise(function (resolve, reject) {
    //return  reject ('s1003');

   return  resolve('testok')
    }).catch(function(err){
        throw  err ;
    });

  
}

function test1(){
return new Promise(function (resolve, reject) {
      return  reject ('s1004');
    // return  resolve('test1ok')
    }).catch(function(err){
         throw  err ;
    });
  
}


test().then(res=>{
     console.log(res)
     return test1()
},err=>{
       throw err  //这里可以指定抛出错误
})

.then(res=>{
      console.log('1')
},err=>{
    //这里判断抛出的谁抛出的
     console.log(err)
})

相关文章

网友评论

      本文标题:Promise

      本文链接:https://www.haomeiwen.com/subject/fyiykctx.html