How to make a Queryable Promise in JavaScript?

Utkarsh Pramod Gupta
2 min readOct 10, 2019

--

ES6 Promises

Promises are one of the most crucial features of JavaScript. It helps developers to deal with the async behavior of the language in a much more efficient manner.

A Queryable-Promise is an extended version of the very natively available Promise object in Javascript. Using a Queryable Promise you can query the status of your promises (Pending, Resolved or Rejected) synchronously. This may not sound much useful to some but you can use it in situations where you want to make an API call and your users are expecting the response within a few seconds, say 3, but the API call is taking longer than that for whatsoever reasons. In such cases, you can synchronously query the status of your Promise wrapped API call (as shown in the example below) after 3 seconds of making the API call and show your users some feedback like, “This is taking longer than expected :( …Please wait”.

class QueryablePromise extends Promise {
constructor (executor) {
super((resolve, reject) => executor(
data => {
resolve(data)
this._status = 'Resolved'
},
err => {
reject(err)
this._status = 'Rejected'
},
))
this._status = 'Pending'
}

get status () {
return this._status
}
}

// Create a promise that resolves after 5 sec
var myQueryablePromise = new QueryablePromise((resolve, reject) => {
setTimeout(() => resolve(), 5000)
})

// Log the status of the above promise every 500ms
setInterval(() => {
console.log(myQueryablePromise.status)
}, 500)

--

--