Can Service Workers respond to synchronous XHR requests?

后端 未结 3 1829
[愿得一人]
[愿得一人] 2021-01-03 23:42

I would like to use Service Workers to enhance an existing web site. In particular, I would like to add better offline support by having Service Workers respond to requests

3条回答
  •  被撕碎了的回忆
    2021-01-04 00:26

    You could create a synchronous effect by chaining asynchronous calls together. It creates indented callbacks - whereas promises would make the code easier to read - but the 2nd Ajax call won't be made until after the 1st one has returned. Note that the 3rd parameter is set to true in both calls.

    // Synchronized Ajax calls using 2 nested Asynchronous calls
    
    // Asynchronous request #1 using traditional API
    const axhr = new XMLHttpRequest();
    axhr.open('GET', '/__so-example__', true);
    axhr.onload = event => {
      console.log("A-XHR: " + axhr.responseText);
    
      // Asynchronous request #2 using traditional API
      const sxhr = new XMLHttpRequest();
      sxhr.open('GET', '/__so-example__', true);
      sxhr.onload = event => {
        console.log("S-XHR: " + sxhr.responseText);
      }
      sxhr.send();
    }
    axhr.send();
    

    It's just an example. I assume that promises could be chained just as easily (but vertically stacked, instead of right indented) to create a synchronous effect.

提交回复
热议问题