我正在尝试为博客平台创建一个构造函数,它内部有许多异步操作.这些包括从目录中获取帖子,解析它们,通过模板引擎发送它们等等.
所以我的问题是,让我的构造函数返回一个promise而不是它们调用的函数的对象是不明智的new
.
例如:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Run Code Online (Sandbox Code Playgroud)
现在,用户可能还没有提供补充Promise链链接:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
Run Code Online (Sandbox Code Playgroud)
这可能会造成问题,因为用户可能会感到困惑,为什么 engine
在施工后无法使用.
在构造函数中使用Promise的原因是有道理的.我希望整个博客在构建阶段后正常运行.然而,在呼叫之后,它似乎几乎无法立即访问该对象new
.
我一直在争论使用的东西,engine.start().then()
或者engine.init()
会返回Promise.但那些看起来也很臭.
编辑:这是在Node.js项目中.
目前,我正在尝试async/await
在类构造函数中使用.这样我就可以获得e-mail
我正在研究的Electron项目的自定义标签.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
Run Code Online (Sandbox Code Playgroud)
但是,目前该项目不起作用,出现以下错误:
Class constructor may not be an async method
Run Code Online (Sandbox Code Playgroud)
有没有办法绕过这个,以便我可以在其中使用async/await?而不是要求回调或.then()?
正如问题所述.我会被允许这样做:
class MyClass {
async constructor(){
return new Promise()
}
}
Run Code Online (Sandbox Code Playgroud)