Skip to content

Instantly share code, notes, and snippets.

@kurtmilam
Last active November 6, 2017 19:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kurtmilam/1f82dc8c90118e68761d to your computer and use it in GitHub Desktop.
Save kurtmilam/1f82dc8c90118e68761d to your computer and use it in GitHub Desktop.
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