Last active
May 26, 2020 12:23
-
-
Save uhyo/f97499872fb0685bd5a4b11fa0f55aef to your computer and use it in GitHub Desktop.
Sync way of obtaining promise result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Promise.prototype.then = (()=> { | |
const _then = Promise.prototype.then; | |
return function(...args) { | |
_then.call(this, (res) => { | |
promiseResultMap.set(this, res); | |
}) | |
this.then = _then; | |
return _then.apply(this, args); | |
} | |
})(); | |
const promiseResultMap = new WeakMap() | |
function getPromiseValue(p) { | |
return promiseResultMap.get(p); | |
} | |
const sleep = (duration)=> new Promise((resolve) => setTimeout(()=>resolve(0), duration)); | |
(()=> { | |
const p = sleep(500); | |
console.log("before", getPromiseValue(p)); | |
p.then(()=> { | |
console.log("after", getPromiseValue(p)); | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment