Skip to content

Instantly share code, notes, and snippets.

@rytmis
Last active January 3, 2019 10:51
Show Gist options
  • Save rytmis/6ce8549c84bc1be0eca25aa2d0bc06ab to your computer and use it in GitHub Desktop.
Save rytmis/6ce8549c84bc1be0eca25aa2d0bc06ab to your computer and use it in GitHub Desktop.
const Promise = require('bluebird');
const findAsync = (predicate, items) => {
if (items.length < 1) {
return Promise.resolve(undefined);
}
const [current, ...rest] = items;
return predicate(current)
.then(match => {
if (match) {
return current;
}
return findAsync(predicate, rest);
});
}
const slowPredicate = (actualPredicate, item) => {
console.log("Starting slow predicate", item);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(actualPredicate(item));
}, 200);
})
}
findAsync((item) => slowPredicate(i => i === "me!", item), ["you", "can't", "find", "me!", "I'm", "hiding"])
.then(found => {
console.log("Found:", found);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment