| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
const nullAbortController = { |
| 13 |
signal: undefined, |
| 14 |
abort: () => {} |
| 15 |
}; |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
function fetchJson( resource, init ) { |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
const controller = window.AbortController ? |
| 29 |
new AbortController() : |
| 30 |
nullAbortController; |
| 31 |
|
| 32 |
const getJson = fetch( resource, Object.assign( {}, init, { |
| 33 |
signal: controller.signal |
| 34 |
} ) ).then( ( response ) => { |
| 35 |
if ( !response.ok ) { |
| 36 |
return Promise.reject( |
| 37 |
'Network request failed with HTTP code ' + response.status |
| 38 |
); |
| 39 |
} |
| 40 |
return response.json(); |
| 41 |
} ); |
| 42 |
|
| 43 |
return { |
| 44 |
fetch: getJson, |
| 45 |
abort: () => { |
| 46 |
controller.abort(); |
| 47 |
} |
| 48 |
}; |
| 49 |
} |
| 50 |
|
| 51 |
module.exports = fetchJson; |