javascript - ES 6 Harmony 异步类方法链接
问题描述
这是一个简单的 JavaScript 示例:
class Test {
constructor() {
this.a = 0;
this.b = 1;
}
doSomething = async () => {
await this.doSomethingChained(1)
.doSomethingChained(2)
.doSomethingChained(3);
};
doSomethingChained = async (x) => {
this.a = this.a + x;
console.log('a is', this.a);
return this;
};
}
然后使用测试方法开始,但这并不重要
test('Vorgang erfassen', async t => {
const t1 = new Test();
await t1.doSomething();
控制台包含以下内容:
a is 1
TypeError: _this2.doSomethingChained(...).doSomethingChained is not a function
我不明白为什么this.a
有效,但return this
不是。我当然可以一个接一个地开始这个方法,但我喜欢使用链接。
doSomething = async () => {
await this.doSomethingChained(1);
await this.doSomethingChained(2);
await this.doSomethingChained(3);
};
奇迹般有效。
a is 1
a is 3
a is 6
解决方案
你可以像下面这样链接你的承诺:
doSomething = async () => {
await this.doSomethingChained(1)
.then(() => this.doSomethingChained(2))
.then(() => this.doSomethingChained(3));
};
推荐阅读
- haskell - 图书馆:“vector-0.12.0.2:高效数组”
- c# - 使用 c# 使用 gsm modam 发送短信,消息长度太短
- forms - 使用唯一键号 Firebase 存储数据库
- amazon-web-services - 从 CloudTrail S3 存储桶获取对象时 S3 访问被拒绝
- javascript - 是否可以使用 javascript 实时检查 window.variable 对象
- javascript - Amcharts:更改整个数据集
- scikit-learn - 使用类权重的网格搜索和 KerasClassifier
- arrays - 获取 ruby 数组中特定模式的出现次数
- node.js - 通过浏览器上的 node.js 将音频流式传输到 Azure 语音 api
- mysql - 从其他人的项目迁移时如何修复“Django:表不存在”?