呈现异步函数的正确方法是什么?
What is the proper way to render an async function?
我有一个函数可以获取一个对象和 returns 从对所述对象的检查中获取一个布尔值。
我需要这个布尔值来决定 HTML 应该是我的 render() 函数的输出。当在我的 render() 函数中调用检查获取的对象的函数时,它总是 returns "undefined",因为它总是评估为真。
我应该如何在适当的时间输出正确的值?谢谢。
async isGreenlisted() {
return fetch(`${WEB_SERVICE_URL}/v2/banners/${this.viewId}`)
.then(res => {
for (let list in res) {
if (res[list].isDisplayed && list === "green") {
console.log("green true");
return true;
}
}
return false;
});
}
render() {
return html`
<style>
paper-button {
color: blue;
}
</style>
<div>
${this.isGreenlisted()
? html`
<paper-button raised @click="${this._onClick}">Disable Powered By</paper-button>
`
: html`
<paper-button raised @click="${this._onClick}">Enable Powered By</paper-button>
`}
</div>
`;
}
}
isGreenlisted()
returns a Promise
所以在三元运算符中,你本质上是在评估承诺本身而不是它将解析的值,并且由于 class实例为 truthy,始终显示第一个模板。
您应该等待承诺的结果,例如使用 lit-html
的 until
directive:
import {until} from 'lit-html/directives/until';
render() {
return html`
${until(
this.isGreenlisted().then(res => res
? html`True`
: html`False`),
html`Loading...`,
)}
`;
}
我有一个函数可以获取一个对象和 returns 从对所述对象的检查中获取一个布尔值。
我需要这个布尔值来决定 HTML 应该是我的 render() 函数的输出。当在我的 render() 函数中调用检查获取的对象的函数时,它总是 returns "undefined",因为它总是评估为真。
我应该如何在适当的时间输出正确的值?谢谢。
async isGreenlisted() {
return fetch(`${WEB_SERVICE_URL}/v2/banners/${this.viewId}`)
.then(res => {
for (let list in res) {
if (res[list].isDisplayed && list === "green") {
console.log("green true");
return true;
}
}
return false;
});
}
render() {
return html`
<style>
paper-button {
color: blue;
}
</style>
<div>
${this.isGreenlisted()
? html`
<paper-button raised @click="${this._onClick}">Disable Powered By</paper-button>
`
: html`
<paper-button raised @click="${this._onClick}">Enable Powered By</paper-button>
`}
</div>
`;
}
}
isGreenlisted()
returns a Promise
所以在三元运算符中,你本质上是在评估承诺本身而不是它将解析的值,并且由于 class实例为 truthy,始终显示第一个模板。
您应该等待承诺的结果,例如使用 lit-html
的 until
directive:
import {until} from 'lit-html/directives/until';
render() {
return html`
${until(
this.isGreenlisted().then(res => res
? html`True`
: html`False`),
html`Loading...`,
)}
`;
}