我想使用 Promise 的值作为这样一个函数的默认参数。
_drawElement(selector, html = this._htmlFrom(selector)) {
console.log(html);
}
_htmlFrom(templateName) {
var templatePath = `${this._templates}/${templateName}.html`;
return fetch(templatePath)
.then((response) => response.ok ? response.text() : null)
}
但我希望 html 是一个字符串 因为我可以用其他方式传递它 而不是 htmlFrom 函数。这里我有一个promise,但我不知道如何检索字符串值(或null)。
好吧,按照SurencPerformance的建议,我这样做了。
async _drawElement(selector, html = this._htmlFrom(selector)) {
var tags = document.querySelectorAll(selector);
if (tags.length == 1) {
console.log(html);
var isPromise = typeof html.then == 'function';
if (isPromise) {
html = await html;
}
...
}
但不知道为什么,_htmlFrom函数被调用了,即使我用html的值调用函数。(为什么即使我给一个字符串作为参数,html也是一个承诺)
你所需要的HTML是异步检索的,不幸的是没有办法等待它的完成。在参数列表中. 你必须在函数的第一行等待它。
async _drawElement(selector, html) {
if (html === undefined) {
html = await this._htmlFrom(selector);
}
console.log(html);
}