Skip to content

Instantly share code, notes, and snippets.

@mike-north
Created October 26, 2014 04:49
Show Gist options
  • Save mike-north/f10b3f8c8579b6dba729 to your computer and use it in GitHub Desktop.
Save mike-north/f10b3f8c8579b6dba729 to your computer and use it in GitHub Desktop.
Run a promise-based operation on each item in an array, in sequence
// An array of data to operate on
var dat = ['a', 'b', 'c', 'd', null, 'e'];
/**
* A long running task to run for each element of the array.
* It must return a promise
*/
function doThing(arg) {
return new Promise(
function (resolve, reject) {
setTimeout(function () {
console.log(arg);
if (arg) {
resolve('resolved - ' + arg);
} else {
reject('Error: falsy value');
}
}, 1000);
}
);
}
/**
* Get a handle on the "resolve" method
* of an initial promise, so we can start
* the work after our chain of promises is
* assembled
*/
var go;
var lastPromise = new Promise(
function (resolve, reject) {
go = resolve;
}
);
/**
* Generate an executor for a given index in the
* array. The outer function will be evaluated
* at promise-chain-assembly time, the inner function
* that's returned will be run at promise-chain-run time
*/
function makeExecutor(arg) {
return function (result /*result of previous task*/ ) {
return doThing(arg);
};
}
/**
* Loop over the array of data to create a promise
* chain
*/
for (var i = 0; i < dat.length; i += 1) {
lastPromise = lastPromise
.then(makeExecutor(dat[i]));
}
/**
* Attach an error handler at the end of the chain
*/
lastPromise.catch(function (err) {
console.err('Error: ', err);
});
// Wait a moment, then start running the tasks
setTimeout(function () {
console.log('and we\'re off!');
go();
}, 500);
@mike-north
Copy link
Author

If you run this in a browser that supports ES6 promises (i.e,. Chrome), you should see the following output

and we're off!
a
b
c
d
null
Error:  Error: falsy value 

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