Use fetch encountered problems ReadableStream is locked

When using fetch encapsulation, I encounter a problem, is to be compatible with the data returned back after the holiday is not the same problem

For example, sometimes json, sometimes string, sometimes Buffer type. And so on, look at the code

let a = null;
fetch(url).then(
  res=> {
return res.json()
}.catch(
  e=>{
  return res.arrayBuffer()
  }
))

This is the case, first do json processing. If not json data will be entered into the catch but this time the catch inside e not what you want, so

then the callback inside of a variable assignment. This time it is compatible with the two data types.

Note that must take json on the top, readablestream method can be called without any arrayBuffer into the catch method. If you have other compatible, you can continue to increase in the catch above

At this point the question is,

Get an error function of the newspaper ReadableStream is locked

This is because the object might only be called once api will be lock, the solution is to call his clone as follows

let a = null;
let data = await fetch(url).then(
  res=> {
a = res.clone().arrayBuffer()
return res.clone().json() }.catch(   e=>{   return a   } ))

You may also have other ways. Note Oh. If you are compatible with a variety of data types. catch use callbacks. See comments in question. .

 

Guess you like

Origin www.cnblogs.com/lisiyang/p/11429906.html