Skip to content

Instantly share code, notes, and snippets.

@ELLIOTTCABLE
Created May 20, 2014 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ELLIOTTCABLE/37979fc70447d2b749b7 to your computer and use it in GitHub Desktop.
Save ELLIOTTCABLE/37979fc70447d2b749b7 to your computer and use it in GitHub Desktop.
return redis.smembersAsync('langs')
.then(function(languages){
// I need to call `articleExists('foo', language)` for each member of `languages`.
// `articleExists` returns a promise; if it does, indeed, exist, then the promise resolves to
// the result I need (a name.)
// if the article does *not* exist, then the promise returned by `articleExists` is rejected,
// and I need to move on to the next element of `languages`
}
@kriskowal
Copy link

return languages.reduceRight(function (next, language) {
    return function () {
        return articleExists("foo", language)
        .then(function () {
            return [name, language];
        }, function (error) {
            return next();
        });
    };
}, function () {
    throw Error("Can't find article");
})();

@petkaantonov
Copy link

var results = [];
return redis.smembersAsync('langs')

.reduce(function(cur, language) {
    return cur.then(function(){
        return articleExists('foo', language);
    }).then(function(existResult) {
        results.push(existResult);
    }).catch(function(e) {});
}, Promise.resolve())

.thenReturn(results);

@spion
Copy link

spion commented May 20, 2014

Procedural

var article = Promise.reject(new Promise.RejectionError("not found")); 
languages.forEach(function(lang) { 
    article = article.error(function(e) { return articleExists('foo', lang); }); 
}); 
return article;

Functional

return languages.reduce(function(article, lang) { 
    return article.error(function(e) { return articleExists('foo', lang); }); 
}, Promise.reject(new Promise.RejectionError("not found"))); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment