Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make a promise wait for a specific object property to be set
// Semi reusable factory for promises waiting on an object property to be defined
function waitForIt (objectToObserve, propertyToObserve) {
return new Promise(function (resolve, reject) {
var checkIt = function (objectToObserve, propertyToObserve){
if (typeof objectToObserve[propertyToObserve] == 'undefined'){
setTimeout(checkIt, 500, objectToObserve, propertyToObserve)
} else {
resolve(objectToObserve[propertyToObserve])
}
}
checkIt(objectToObserve, propertyToObserve)
})
}
// Sampe object
var foo = {
"envTime":12345678,
"aDependency":"{{envTime}}",
"bDependency":"{{extJSON.response.answer}}", // <-- waiting on this.extJSON.response.answer to be defined
"extJSON":{
"GET":"http://example.com/some.json",
"response":{}
}
}
// Create a promise using our factory
var waitingForTheAnswer = waitForIt(foo.extJSON.response, 'answer')
.then(function (val) {
console.log('It is finished, and the answer is', val)
})
// Wait a little, then add the 'answer' property to our object
setTimeout(function (objectToSet, propToSet) {
objectToSet[propToSet] = 42
}, 50, foo.extJSON.response, 'answer')
// Wait a little longer and verify that our promise was fulfilled
setTimeout(function (promiseToCheck) {
console.log('promiseToCheck.isFulfilled()', promiseToCheck.isFulfilled())
}, 600, waitingForTheAnswer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.