mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
lib/router: improve aborting xhr
This commit is contained in:
parent
3e721b6878
commit
a8c6b9e57a
|
@ -120,20 +120,13 @@ export default class Router {
|
|||
const route = toRoute(parse(url).pathname)
|
||||
|
||||
let data = this.components[route]
|
||||
if (data) return data
|
||||
|
||||
if (!data) {
|
||||
let cancel
|
||||
let cancelled = false
|
||||
|
||||
const componentUrl = toJSONUrl(route)
|
||||
data = await new Promise((resolve, reject) => {
|
||||
this.componentLoadCancel = cancel = () => {
|
||||
cancelled = true
|
||||
if (xhr.abort) xhr.abort()
|
||||
|
||||
const err = new Error('Cancelled')
|
||||
err.cancelled = true
|
||||
reject(err)
|
||||
}
|
||||
|
||||
const xhr = loadComponent(componentUrl, (err, data) => {
|
||||
|
@ -146,15 +139,8 @@ export default class Router {
|
|||
this.componentLoadCancel = null
|
||||
}
|
||||
|
||||
// we update the cache even if cancelled
|
||||
if (data) this.components[route] = data
|
||||
|
||||
if (cancelled) {
|
||||
const err = new Error('Cancelled')
|
||||
err.cancelled = true
|
||||
throw err
|
||||
this.components[route] = data
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
|
@ -242,6 +228,11 @@ function loadJSON (url, fn) {
|
|||
xhr.onerror = () => {
|
||||
fn(new Error('XHR failed. Status: ' + xhr.status))
|
||||
}
|
||||
xhr.onabort = () => {
|
||||
const err = new Error('XHR aborted')
|
||||
err.cancelled = true
|
||||
fn(err)
|
||||
}
|
||||
xhr.open('GET', url)
|
||||
xhr.send()
|
||||
|
||||
|
|
Loading…
Reference in a new issue