You can use array reduce, but for this situation you might not want to consildate your data before making any fs calls.
With array reduce:
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
rows.map(function(row) {
return new Buffer(JSON.stringify(row));
}).concat(['end'])
.reduce(function(a, b) {
return a.then(function() {
return fs.appendFileAsync(filename, b);
})
}, Promise.resolve(''))
.then(function(res) {
// all done here
})
.catch(function(err) {
throw err;
});
In my opinion the following would be just fine
var data = rows.map(function(row) {
return JSON.stringify(row);
})
.concat(['end'])
.join('');
fs.appendFileAsync(filename, data).then(function(res) {
});
Once you create a promise, its going. Array reduce is a good way to ensure sequential execution. You are essentially building a chain of promises. In your situation it would work, but is it the best call? Thats going to be a fs call for each row and added complexity to the operation.