Skip to content

Instantly share code, notes, and snippets.

@tomchen
Created January 19, 2021 15:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomchen/cb95ace46bbcc3486dc007b9d88a1633 to your computer and use it in GitHub Desktop.
Save tomchen/cb95ace46bbcc3486dc007b9d88a1633 to your computer and use it in GitHub Desktop.
Play with Promise
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