了解获取响应中的承诺行为

时间:2020-04-27 01:35:08

标签: xml http promise fetch

这是原始帖子的修改。我能够将问题归结为一个问题,尽管我有一个解决方法,但我想了解有什么不同(即,我不完全了解为什么它在做它正在做的事情……并想要这样做)

上下文:这是在浏览器中运行的JS,它调用代理服务器来解决CORS问题。代理服务器正在从RSS提要中获取XML。

浏览器的JS代码表现出以下行为:

fetch(example.com/rss)
    .then(response => response.text())
    .then(str => new window.DOMParser().parseFromString(str,"text/xml"))
    .then(data => { 
          const items = data.querySelectorAll("item");
          //data is empty here so error
    });

当我消除中间的then并在另一个处理程序中执行parseFromString时,我得到了预期的结果:

fetch(example.com/rss)
    .then(response => (response.text())
    .then(data => { 
            var data = new DOMParser().parseFromString(data,"text/xml");
            const items = data.querySelectorAll("item");
            //works!!!
}

谁能解释行为上的差异? Window.DOMParsernew DOMParser之间有区别吗?

0 个答案:

没有答案