我想实现经典的方法链模式,最终的用法应该是
let nodes = [];
let DB = {
self:this,
push: (i) => new Promise((resolve, reject) => {
nodes.push(i)
resolve(this)
})
}
这是当前的代码,显然不起作用,我不清楚如何返回对DB本身的引用来解决这个承诺
{{1}}
答案 0 :(得分:2)
只有class
或function
个实例有this
个引用。
class DB {
constructor() {
this.nodes = [];
this.promise = Promise.resolve();
}
push(i) {
this.nodes.push(i);
return this;
}
pushAsync(i) {
return new Promise((resolve) => {
this.nodes.push(i);
resolve();
});
}
pushAsyncChain(i) {
this.promise.then(() => {
this.promise = new Promise((resolve) => {
this.nodes.push(i);
resolve();
});
});
return this;
}
then(callback) {
this.promise.then(callback);
}
}
const db = new DB();
db.push(2).push(3);
db.pushAsync(4).then(() => db.pushAsync(5));
db
.pushAsyncChain(6)
.pushAsyncChain(7)
.then(() => console.log(db.nodes)); // or await db.promise; console.log(db.nodes);