无法参数传递给类方法,

问题描述:

我有一个类:无法参数传递给类方法,

'use strict'; 
class aClass { 
    a() { 
     return new Promise((resolve, reject) => { 
      if (1 != 1) { 
       reject(new Error('error')); 
      } else { 
       resolve('a'); 
      } 
     }); 
    } 
    b(b) { 
     return new Promise((resolve, reject) => { 
      if (1 != 1) { 
       reject(new Error('error')); 
      } else { 
       resolve('b'); 
      } 
     }); 
    } 
    c(c) { 
     console.log(c); 
    } 


    do() { 
     this.a() 
      .then((a) => { 
       this.b(a); 
      }) 
      .then((b) => { 
       console.log(b); 
       this.c(b); 
      }).catch((error) => { 
       console.log('err', error); 
      }); 
    } 
} 

module.exports = aClass; 

当我创建的类的对象,并调用do()方法:

let anObject = new aClass(); 
anObject.do(); 

“undefined”在控制台中记录了两次。这意味着,在b()方法的参数都没有传递给一个承诺的决心:resolve('b');

同时,如果我不使用类的方法,但添加代码直接进入回调:

do() { 
    this.a() 
     .then((a) => { 
      return new Promise((resolve, reject) => { 
       if (1 != 1) { 
        reject(new Error('error')); 
       } else { 
        resolve('b'); 
       } 
      }); 
     }) 
     .then((b) => { 
      console.log(b); 
      this.c(b); 
     }).catch((error) => { 
      console.log('err', error); 
     }); 
} 

一切正常, “b”在控制台中记录了两次。

我使用nodejs作为此示例,babeljs作为转换器。 当我使用类方法时,为什么不传递参数?是否有任何范围限制,或者它是一个转译问题?

+2

如果你'返回this.b(A);'这一切都很好,或删除{}'左右this.b(一)'它按预期工作再次...学习箭头函数语法知道为什么这是 –

+0

谢谢,我忘了返回一个可靠的对象。 –

在:

.then((a) => { 
    this.b(a); 
}) 

你不return荷兰国际集团任何事情,所以undefined返回代替 - 这是进入

.then((b) => { 
    console.log(b); 
    this.c(b); 
}) 

,无论其记录并将其传递到c,这也记录它。

试着改变你的代码:

.then((a) => { 
    return this.b(a); 
}) 
+0

非常感谢。 –