Skip to content

Instantly share code, notes, and snippets.

@owenallenaz
Created February 20, 2014 04:21
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 owenallenaz/9107058 to your computer and use it in GitHub Desktop.
Save owenallenaz/9107058 to your computer and use it in GitHub Desktop.

Example showing async.waterfall which functions semantically the same as promises.

<script src="http://cdnjs.cloudflare.com/ajax/libs/async/1.22/async.min.js"></script>

<script>
	// waterfall wrapper to try/catch each method in a waterfall
	var catchWaterfall = function(arr, cb) {
		var calls = [];
		arr.forEach(function(val) {
			calls.push(function() {
				try {
					val.apply(val, arguments)
				} catch(err) {
					arguments[arguments.length - 1](err);
				}
			});
		});
		
		async.waterfall(calls, cb);
	}
		

	// Complete task using async
	var asyncTask = function(cb) {
		catchWaterfall([
			function(cb) {
				cb(null, "async foo");
			},
			function(data, cb) {
				cb(null, data + " bar");
			}
		], function(err, result) {
			cb(err, result);
		});
	}
	
	asyncTask(function(err, data) {
		if (err) {
			// if err handle err
		}
		
		console.log(data);
		// foo bar
	});
	
	// Complete task using native Promise
	var promiseTask = function(cb) {
		return Promise.resolve("promise foo").then(function(data) {
			return data + " baz";
		});	
	}

	promiseTask().then(function(data) {
		console.log(data);
		// foo bar
	}, function(err) {
		// if err handle err
	});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment