[英]async/await not working and i dont see why
function projectHTML(e) {
let proj = await getProject(e.srcElement.dataset.id);
console.log(proj);
return `
<div id="Project">
<h1>${proj.name}</h1>
<p>Description: ${proj.description}</p>
</div>
`;
}
async function getProject(id) {
try {
let res = await fetch(`http://127.0.0.1:5000/api/projects/${id}`);
res = await res.json();
return res;
} catch (e) {
console.error(e);
}
}
The first function, projectHTML()
, is being called from another file. 从另一个文件中调用第一个函数projectHTML()
。 I am able to return the value from function gethelp()
, ProjectsHTML()
. 我可以从函数gethelp()
和ProjectsHTML()
返回值。 I can even log it in the console and indeed see it's correct. 我什至可以将其记录在控制台中,并确实是正确的。 However, it won't load up into the template literal that I have. 但是,它不会加载到我拥有的模板文字中。 Please, someone lend a hand. 拜托,有人帮忙。 I tried doing async...await
in try blocks in ProjectsHTML()
and still no luck. 我尝试做async...await
在ProjectsHTML()
try块中async...await
,仍然没有运气。
async function getProject(id) {
try {
const res = await fetch(`http://127.0.0.1:5000/api/projects/${id}`);
return res.json();
} catch (e) {
console.error(e);
}
}
getProject(id).then((data) => {
console.log(data)
})
You need to modify your code like following: 您需要像下面这样修改代码:
async function projectHTML(e) {
let proj = await getProject(e.srcElement.dataset.id);
console.log(proj)
return `<div id="Project">
<h1>${proj.name}</h1>
<p>Description: ${proj.description}</p>
</div>`;
};
If I am not wrong above function is an event handler and you are using passing it in your html
. 如果我没看错,上面的函数是一个事件处理程序,您正在使用在html
传递它。 If not, and you are calling it from another function, you need to use await
while calling this function: 如果不是,并且您正在从另一个函数调用它,则在调用此函数时需要使用await
:
await projectHtml(e)
Let me know if this helps. 让我知道是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.