2

我有一堂课:

'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();

“未定义”在控制台中记录了两次。这意味着在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作为转译器。为什么我使用类方法时不传递参数?是否有任何范围限制,或者这是一个转译器问题?

4

1 回答 1

2

在:

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

你什么都没有return,所以undefined被返回 - 这是进入

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

既记录它并将其传递给c,它也记录它。

尝试将您的代码更改为:

.then((a) => {
  return this.b(a);
})
于 2015-11-08T08:29:23.520 回答