天天看点

JavaScript ES6 Fetch API时需要注意的一个Cookie问题

When I am doing a test of comparison between Stateful and Stateless BSP application ( mentioned in blog Stateless and Stateful – Different behavior in application side ), I meet with a strange issue.

The conclusion is stateful BSP application will handle request sequentially. Suppose in client I send two request A and B to server. Request A takes 3 seconds to finish and B 2 seconds.

JavaScript ES6 Fetch API时需要注意的一个Cookie问题

The request is sent via jQuery API.

It means for stateful application, I will observe the following timeline in Chrome network tab:

(1) the start time of both request are almost the same, since I send out two request in client code almost at the same time.

(2) even though the second request itself takes 2 seconds to finish, the total processing time for it is 3 seconds waiting for A to finish first + 2 seconds = 5 seconds in the end.

JavaScript ES6 Fetch API时需要注意的一个Cookie问题

<%@page language="abap" %>
<%@extension name="htmlb" prefix="htmlb" %>
<!DOCTYPE html>
<html>
<head>
<title>Jerry Test Stateful</title>
</head>
<body>
<button onclick="fire()">Fire two request</button>
<script>
function wrapperOnFetch(url){
  fetch(url).then(function(response){
    return response.json();
  }).then(function(json){
      console.log(url + ":" + json.message);
  });
}
function fire(){
  wrapperOnFetch("first.json");
  wrapperOnFetch("second.json");
}
</script>
</body>
</html>
      

the testing request for stateful application looks as below this time:

JavaScript ES6 Fetch API时需要注意的一个Cookie问题
JavaScript ES6 Fetch API时需要注意的一个Cookie问题
JavaScript ES6 Fetch API时需要注意的一个Cookie问题
function wrapperOnFetch(url){
 // enable session cookie sent with request
  fetch(url,{ credentials:"include" }).then(function(response){
    return response.json();
  }).then(function(json){
      console.log(url + ":" + json.message);
  });
}
      

After this change the stateful BSP application behaves as expected: the requests are handled in sequence.

继续阅读