简体   繁体   English

Javascript – 将多个值返回给链接的“then”函数

[英]Javascript – return multiple values to chained “then” functions

I have a fetch call with a couple of then functions.我有一个带有几个then函数的 fetch 调用。 In one of the then functions I'd like to pass two returned variables to the next then function.在其中一个函数中,我想将两个返回的变量传递给下一个然后function。 It doesn't work though.但它不起作用。

.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; 
})    

Accessing the thehtml() function in the last then() throws a is not a function error .在最后一个then()中访问 thehtml() function 会抛出 a is not a function 错误 Thanks for any tips!感谢您的任何提示!

You can modify the code like below, through which you can get access to the title and main in the other then method.您可以像下面这样修改代码,通过它您可以在另一个then方法中访问titlemain

.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; 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM