如何将自定义属性或方法添加到Promise? [英] How to add a custom property or method to a promise?
问题描述
常规承诺具有心爱的 .then()
和 .catch()
功能.
Regular promises have the beloved .then()
and .catch()
functions.
当 promising
检索本身具有返回诺言的属性的对象时,我们会找到如下的诺言链:
When promising
to retrieve an object that itself has properties that return promises we find chains of promises such as the following:
require("clientside-view-loader")
.then((view)=>
return view.load("clientside-view-modal-login_signup");
})
.then((compiler)=>{
return compiler.generate()
})
.then((modal)=>{
document.body.appendChild(modal);
modal.show("login");
})
这太丑了!
我们如何修改附加自定义属性的承诺,以便将以上内容转换为以下内容?
How can we modify a promise to attach a custom property so that we can convert the above into the following?
require("clientside-view-loader")
.load("clientside-view-modal-login_signup")
.generate()
.then((modal)=>{
document.body.appendChild(modal);
modal.show("login");
})
请注意,这些示例使用 clientside-require
require
而不是 nodejs
require
note, these examples use the clientside-require
require
and not the nodejs
require
推荐答案
我们如何修改承诺以附加自定义属性,以便将以上内容转换为以下内容?
How can we modify a promise to attach a custom property so that we can convert the above into the following?
您根本不修改承诺.您只需为上述承诺链实现构建器模式即可.
You don't modify promises at all. You just implement the builder pattern for the above promise chain.
class ClientSideViewLoader {
constructor(p = Promise.resolve()) {
this.promise = p;
}
static init() {
return new this(require("clientside-view-loader"));
}
load(x) {
return new this.constructor(this.promise.then(view =>
view.load(x)
));
}
generate() {
return new this.constructor(this.promise.then(compiler =>
compiler.generate()
));
}
then(...args) {
return this.promise.then(...args);
}
}
ClientSideViewLoader.init()
.load("clientside-view-modal-login_signup")
.generate()
.then(modal => {
document.body.appendChild(modal);
modal.show("login");
})
无需做任何复杂的事情,例如将 Promise
继承为子类.如果需要,还可以动态生成所有这些方法.
No need to do anything complicated like subclassing Promise
. If you want, you can also dynamically generate all these methods.
这太丑了!
好吧,如果您正在寻找漂亮的Promise代码,则只需使用现代的 async
/ await
语法,而不是 then
回调:
Well, if you were looking for beautiful promise code, you would simply use modern async
/await
syntax instead of then
callbacks:
const view = await require("clientside-view-loader");
const compiler = await view.load("clientside-view-modal-login_signup");
const modal = await compiler.generate();
document.body.appendChild(modal);
modal.show("login");
这篇关于如何将自定义属性或方法添加到Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!