Skip to content

Commit

Permalink
Updated async to support chained maps
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter West committed May 1, 2012
1 parent 74a6248 commit 085918a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
18 changes: 15 additions & 3 deletions async.js
Expand Up @@ -5,6 +5,7 @@
// TODO
// Add fail event
// Prevent multiple firing?
// Make it work for falsey values

var async = exports || {};
var nothing = function() {};
Expand All @@ -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]; },
Expand All @@ -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;
};

Expand Down
26 changes: 24 additions & 2 deletions async_test.js
Expand Up @@ -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) {
Expand All @@ -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(",")); });
.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(); })

0 comments on commit 085918a

Please sign in to comment.