Take a look at async.js, and especially its control flow statements, such as each
whilst
and until
.
Using async.js you can get what you want to have.
In your actual situation what you want is the each
function (which has formerly been known as forEach
), respectively the eachSeries
function which does not run the single iterations in parallel, but in serial (see the documentation for eachSeries for details).
To provide an example:
async.eachSeries([ 2, 3, 5, 7, 11 ], function (prime, callback) {
console.log(prime);
callback(); // Alternatively: callback(new Error());
}, function (err) {
if (err) { throw err; }
console.log('Well done :-)!');
});
This will iterate over the array of prime numbers and print them in the correct order, one after each other, and finally print out Well done :-)!
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…