This commit is contained in:
Dmitry Vasilev
2022-12-23 02:14:38 +08:00
parent 4dbc7c26e2
commit 5be750b424
6 changed files with 61 additions and 75 deletions

View File

@@ -1,78 +1,37 @@
export const patch_promise = window => {
if(window.Promise.Original != null) {
if(window.Promise.__patched) {
// already patched
return
}
class PromiseRecordChildren extends Promise {
then(on_resolve, on_reject) {
let children = window.get_children()
if(children == null) {
children = []
window.set_children(children)
}
return super.then(
on_resolve == null
? null
: value => {
window.set_children(children)
return on_resolve(value)
},
const _then = Promise.prototype.then
on_reject == null
? null
: error => {
window.set_children(children)
return on_reject(error)
Promise.prototype.then = function then(on_resolve, on_reject) {
let children = window.get_children()
if(children == null) {
children = []
window.set_children(children)
}
const make_callback = cb => cb == null
? null
: value => {
const current = window.get_children()
window.set_children(children)
try {
return cb(value)
} finally {
window.set_children(current)
}
)
}
}
class PromiseWithStatus extends window.Promise {
constructor(fn) {
let status
let is_constructor_finished = false
const p = new PromiseRecordChildren(
(resolve, reject) => {
fn(
(value) => {
if(value instanceof window.Promise.Original) {
value
.then(v => {
p.status = {ok: true, value: v}
resolve(v)
})
.catch(e => {
p.status = {ok: false, error: e}
reject(e)
})
} else {
status = {ok: true, value}
if(is_constructor_finished) {
p.status = status
}
resolve(value)
}
},
(error) => {
status = {ok: false, error}
if(is_constructor_finished) {
p.status = status
}
reject(error)
},
)
}
)
is_constructor_finished = true
p.status = status
return p
}
return _then.call(
this,
make_callback(on_resolve),
make_callback(on_reject),
)
}
PromiseWithStatus.Original = window.Promise
window.Promise = PromiseWithStatus
window.Promise.__patched = true
}