From 44b69a46ec7b276d841b97e5736eaa2d3a65e6b0 Mon Sep 17 00:00:00 2001 From: Kris Zyp Date: Sat, 13 Nov 2010 06:55:14 -0700 Subject: [PATCH] Add allKeys --- lib/promise.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/promise.js b/lib/promise.js index df6d366..8fcabb3 100644 --- a/lib/promise.js +++ b/lib/promise.js @@ -475,6 +475,34 @@ exports.all = function(array){ return deferred.promise; }; +/** + * Takes a hash of promises and returns a promise that is fulfilled once all + * the promises in the hash keys are fulfilled + * @param hash The hash of promises + * @return the promise that is fulfilled when all the hash keys is fulfilled, resolved to the hash of results + */ +exports.allKeys = function(hash){ + var deferred = new Deferred(); + var array = Object.keys(hash); + var fulfilled = 0, length = array.length; + var results = {}; + if (length === 0) deferred.resolve(results); + else { + array.forEach(function(key){ + exports.when(hash[key], + function(value){ + results[key] = value; + fulfilled++; + if(fulfilled === length){ + deferred.resolve(results); + } + }, + deferred.reject); + }); + } + return deferred.promise; +}; + /** * Takes an array of promises and returns a promise that is fulfilled when the first * promise in the array of promises is fulfilled