javascript - Javascript – 将多个值返回给链接的“then”函数
问题描述
我有一个带有几个then函数的 fetch 调用。在其中一个then函数中,我想将两个返回的变量传递给下一个then函数。但它不起作用。
.then(text => {
let content = new DOMParser().parseFromString(text, "text/html");
let main = content.querySelector('main').innerHTML;
let title = content.querySelector('title').innerHTML;
function thehtml() {
return {
main, title
}
}
})
.then(thehtml => {
let theParsedHtml = thehtml();
document.querySelector('main').innerHTML = theParsedHtml.main;
document.title = theParsedHtml.title;
})
在最后一个then()中访问 thehtml() 函数会抛出一个is not a function error。感谢您的任何提示!
解决方案
您可以像下面这样修改代码,通过它您可以访问另一个方法中的title
and 。main
then
.then(text => {
let content = new DOMParser().parseFromString(text, "text/html");
let main = content.querySelector('main').innerHTML;
let title = content.querySelector('title').innerHTML;
return {
main, title
}
})
.then(thehtml => {
document.querySelector('main').innerHTML = thehtml.main;
document.title = thehtml.title;
})