Created
October 26, 2014 04:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you run this in a browser that supports ES6 promises (i.e,. Chrome), you should see the following output