嵌套Async函数调用返回[object Promise]问题(已用.then仍异常)
问题原因与解决方案:文章标题显示[object Promise]的异步问题
问题原因
GetAuthor是async函数,这类函数默认返回Promise对象,而非直接返回最终的作者名称。- 你在模板字符串中直接调用
${GetAuthor(data.author_id)}时,异步请求还未完成,此时插入的是未resolved的Promise对象,转成字符串后就显示为[object Promise]。 - 虽然
GetAuthor内部用了await,但外层调用时没有等待这个Promise完成,直接取了它的返回值(Promise)进行插值。
解决方案
方案1:在回调中使用async/await等待结果
修改GetArticle的第二个then回调为async函数,通过await等待GetAuthor返回的Promise完成,拿到真实的作者名称后再插入模板:
async function GetArticle() { const options = { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: articleID }) }; fetch("/get-article", options) .then((response) => response.json()) .then(async (data) => { console.log(data); // 等待作者名称请求完成 const authorName = await GetAuthor(data.author_id); const newElement = document.createElement("div"); newElement.classList.add("w-75", "m-4"); newElement.innerHTML = ` <h2>${data.title} uploaded by ${authorName}</h2> `; articleParent.appendChild(newElement); }) .catch((error) => console.error("Error:", error)); }
方案2:用链式then处理嵌套异步
如果不想用async/await,可以通过嵌套then等待GetAuthor的结果:
function GetArticle() { const options = { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: articleID }) }; fetch("/get-article", options) .then((response) => response.json()) .then((data) => { console.log(data); // 先请求作者名称,拿到结果后再创建DOM return GetAuthor(data.author_id).then(authorName => { const newElement = document.createElement("div"); newElement.classList.add("w-75", "m-4"); newElement.innerHTML = ` <h2>${data.title} uploaded by ${authorName}</h2> `; articleParent.appendChild(newElement); }); }) .catch((error) => console.error("Error:", error)); }
补充说明
异步函数的核心是:Promise对象需要被等待(await或then)才能拿到最终结果,直接使用Promise对象会显示其默认的字符串形式。你的控制台能正常输出作者名称,是因为GetAuthor内部的then已经处理了异步结果,但这个结果没有传递到外层的模板字符串中。
内容的提问来源于stack exchange,提问作者Ryolu
相关产品推荐
相关产品推荐

