Skip to content

SunShinewyf/promise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 

Repository files navigation

this repository is about a test of promise and the source code about promise which is built by myself

在研究过程中,总结promise中的几个易错点:

(1)在then中如果不返回promise对象或者不throw出一个错误对象,也就是如果没有任何返回,则默认返回undefined,则后面的then中的回调函数接收到的将是undefined. 后面的都将是undefined,例如下面的例子:

    asyncFun1().then(function(data1){
        asyncFunc2(data1)
    }).then(function(data2){
        asyncFunc3(data2)
    }).then(res=>console.log(res))

上面的例子中由于then里面的回调函数没有返回任何信息,那么传给后面的then就是undefined,上面的例子最好改为如下:

   asyncFun1().then(function(data1){
        return asyncFunc2(data1)
    }).then(function(data2){
        return asyncFunc3(data2)
    }).then(res=>console.log(res))

(2)缺少catch

如果在promise的链式调用里面缺少catch,那么如果在中间某个环节发生错误,将不会被捕获,也就是控制台将看不到任何错误,不利于调试错误,定位问题,上面的例子就是典型的这样,可以改成下面这样:

    asyncFun1().then(function(data1){
        return asyncFunc2(data1)
    }).then(function(data2){
        return asyncFunc3(data2)
    }).then(res=>console.log(res))
    .catch(err=>console.log(err))

(3)catchthen(null,fn)之间的差异

catch其实是then(null,fn)的一种语法糖实现,但是两者并不等价,例如:

   asyncFun1().then(function(data){
       throw new Error('hava an error')
   }).catch(function(err){
       //捕获到错误 Error('hava an error')
   })
  
  asyncFun1().then(function(data){
      throw new Error('hava an Error');
  },function(res){
      //此时捕获不到错误 Error('have an Error')
  })

也就是then里面的reject回调函数不会处理resolve回调函数里面抛出的错误

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published