Created
January 19, 2021 15:47
-
-
Save tomchen/cb95ace46bbcc3486dc007b9d88a1633 to your computer and use it in GitHub Desktop.
Play with Promise
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
const makeQueryablePromise = (promise) => { | |
if (promise.isFulfilled) { | |
return promise | |
} | |
let isPending = true | |
let isRejected = false | |
let isFulfilled = false | |
const result = promise.then( | |
(value) => { | |
isFulfilled = true | |
isPending = false | |
return value | |
}, | |
(error) => { | |
isRejected = true | |
isPending = false | |
throw error | |
} | |
) | |
result.isFulfilled = () => isFulfilled | |
result.isPending = () => isPending | |
result.isRejected = () => isRejected | |
return result | |
} | |
const logPromise = (promise) => { | |
const myPromise = makeQueryablePromise(promise) | |
console.log('Initial fulfilled:', myPromise.isFulfilled()) //false | |
console.log('Initial rejected:', myPromise.isRejected()) //false | |
console.log('Initial pending:', myPromise.isPending()) //true | |
myPromise | |
.then((value) => { | |
console.log(value) // "Yeah!" | |
console.log('Final fulfilled:', myPromise.isFulfilled()) //true | |
console.log('Final rejected:', myPromise.isRejected()) //false | |
console.log('Final pending:', myPromise.isPending()) //false | |
}) | |
.catch((error) => { | |
console.log(error) // "No!" | |
}) | |
} | |
const promiseAfterNSec = (n, willBeResolved) => | |
new Promise((resolve, reject) => { | |
setTimeout(() => { | |
willBeResolved ? resolve('Yes!') : reject('No!') | |
}, n * 1000) | |
}) | |
const asyncWrappedPromise = async (promise) => { | |
try { | |
return await promise | |
} catch (error) { | |
throw error | |
} | |
} | |
// logPromise(promiseAfterNSec(2, true)) | |
// logPromise(asyncWrappedPromise(promiseAfterNSec(2, true))) | |
// logPromise(promiseAfterNSec(2, false)) | |
logPromise(asyncWrappedPromise(promiseAfterNSec(2, false))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment