首页 > fetch 如何同时发起两个请求?

fetch 如何同时发起两个请求?

用 ajax 的话,知道方案,在这里 Multiple Simultaneous Ajax Requests (with one callback) in jQuery,

$.when(firstPromise, secondPromise).then(function(firstData, secondData) {
  // do something
});

那如果用 fetch 的话,该如何写呢?

根据传统 Ajax 已死,Fetch 永生尝试了一下如下代码,但是浏览器还不支持 await 吧。

fetchTwo(url1, url2);

function fetchTwo(req1, req2) {
    try {
        let res1 = await fetch(req1);
        let res2 = await fetch(req2);
        let data1 = await res1.text();
        let data2 = await res2.text();
        console.log(data1);
        console.log(data2);
    } catch (e) {
        console.log("Oops, error", e);
    }
}

好吧。其实本质需求是,希望用模板引擎 mustache,然后,需要同时获取模板数据, 于是考虑发起两个请求,并且希望用 fetch。

另外一个办法是,在 Server 端先 mustache 渲染好,再一个fetch 直接拿过来。但是目前找到的 ASP.NET MVC mustache 版本有点问题。

服务器端 mustache.js 运行又还没有找到方案与 MVC 集成。为此还试了一下 React.NET,装了一个 ...V8,结果还是客户端执行的。

所以只好继续考虑 Client 端的 mustache.js,发起两个请求再渲染。

解决方案:

var urls = ["html1.html", "html2.html"];
Promise.all(urls.map(url =>
    fetch(url).then(resp => resp.text())
)).then(texts => {
    console.log(texts);
});

执行结果:

方案兼容性(Promise + fetch):

polyfill

参考:

How can I fetch an array of URLs with Promise.all?


Promise.all()?
但是IE还不支持

【热门文章】
【热门文章】