diff --git a/async.js b/async.js index 134b305..3c8defa 100644 --- a/async.js +++ b/async.js @@ -5,6 +5,7 @@ // TODO // Add fail event // Prevent multiple firing? +// Make it work for falsey values var async = exports || {}; var nothing = function() {}; @@ -17,7 +18,8 @@ async.promise = function(fn) { var promise = {}; promise.next = { success: function() { - promise.succeeded = arguments[0]; + promise.succeeded = true; + promise.result = arguments[0]; if (promise.success) promise.success(); }, fail: function() { promise.failed = arguments[0]; }, @@ -27,14 +29,24 @@ async.promise = function(fn) { // Adds then method to the promise promise.then = function(success, fail) { var newPromise = create(); - promise.success = function() { - var value = success.call(newPromise.next, promise.succeeded); + success.call(newPromise.next, promise.result); }; if (promise.succeeded) promise.success(); return newPromise; }; + // Adds map method to the promise + promise.map = function(success, fail) { + var newPromise = create(); + promise.success = function() { + async.map(promise.result, success).then(function(result) { + newPromise.next.success(result); + }); + }; + if (promise.succeeded) promise.success(); + return newPromise; + }; return promise; }; diff --git a/async_test.js b/async_test.js index 2ee64c8..91db8ff 100644 --- a/async_test.js +++ b/async_test.js @@ -12,7 +12,8 @@ async.promise(function() { var next = this; setTimeout(function() { next.success(value); }, 10); }) -.then(function(f) { console.log(f); }); +.then(function(f) { console.log(f); this.success(); }) +.then(function() { console.log("--------------"); }); //Runs a function with asynchronous behaviour on an array of items async.map([1,2,3,4,5,6], function(item, i) { @@ -21,4 +22,25 @@ async.map([1,2,3,4,5,6], function(item, i) { next.success(item-1); }, 10); }) -.then(function(i) { console.log(i.join(",")); }); \ No newline at end of file +.then(function(i) { console.log(i.join(",")); this.success(); }) +.then(function() { console.log("--------------"); }); + +//Runs a function with asynchronous behaviour on an array of items, twice +async.map([1,2,3], function(item, i) { + var next = this; + setTimeout(function() { + next.success(item); + }, 50); +}) +.map(function(item) { console.log(item); this.success(); }) +.then(function() { console.log("--------------"); }) + +//Runs a function with asynchronous behaviour on an array of items, twice +async.promise(function() { + var next = this; + setTimeout(function() { + next.success([4,5,6]); + }, 180); +}) +.map(function(item) { console.log(item); this.success(item); }) +.map(function(item) { console.log(item); this.success(); }) \ No newline at end of file