Skip to content

Instantly share code, notes, and snippets.

@shuding
Forked from gaearon/observeStore.js
Created January 28, 2016 06:01
Show Gist options
  • Save shuding/a2e9a349e625de54333e to your computer and use it in GitHub Desktop.
Save shuding/a2e9a349e625de54333e to your computer and use it in GitHub Desktop.
Wait for some condition to become true on a Flux store, useful for react-router async transition hooks
// Usage example:
//
// willTransitionTo(transition, params, query, callback) {
// observeStore(DraftStore, s => s.isLoaded()).then(() => {
// if (DraftStore.isMissingTitle()) {
// transition.redirect('composeDraft', params);
// }
// }).finally(callback);
// }
'use strict';
var Promise = require('bluebird');
function observeStore(store, predicate) {
var performCheck;
return new Promise(resolve => {
performCheck = () => {
if (predicate.call(null, store)) {
resolve();
}
};
store.addChangeListener(performCheck);
performCheck();
}).finally(() => {
store.removeChangeListener(performCheck);
});
}
module.exports = observeStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment