Reputation: 5451
I'd like to use promises with NodeJS but it seems not working as expected.
I'd like to see LOG 1
, LOG 2
and LOG 3
for all files in this order. And LOG 4
is hidden...
But I get this :
LOG 1
LOG 3
LOG 1
LOG 3
LOG 1
LOG 3
SUCCESS LOG 2
SUCCESS LOG 2
SUCCESS LOG 2
SUCCESS LOG 2
My code :
var filePromise = _.map(files, function(file) {
var filePath = './sql/' + file;
fs.lstat(filePath, function(err, stats) {
if (stats.isFile() && file !== '.gitignore' && file !== 'index.js') {
fs.readFile(filePath, 'utf-8', function(err, data) {
console.log('LOG 1');
db.query(data).then(function() {
console.log(colors.green('SUCCESS LOG 2'));
}).catch(function() {
console.log(colors.red('ERROR LOG 2'));
});
console.log('LOG 3');
});
}
});
});
Promise.all(filePromise).then(function() {
console.log(colors.green('LOG 4'));
});
Upvotes: 0
Views: 92
Reputation: 1540
In order for filePromise
to contain a collection of promises, you need to return a promise for each iteration of your map call. Only then will the call to Promise.all
be evaluated correctly.
var filePromise = _.map(files, function(file) {
return new Promise(function(resolve, reject) {
var filePath = './sql/' + file;
fs.lstat(filePath, function(err, stats) {
if (stats.isFile() && file !== '.gitignore' && file !== 'index.js') {
fs.readFile(filePath, 'utf-8', function(err, data) {
console.log('LOG 1');
db.query(data).then(function() {
console.log(colors.green('SUCCESS LOG 2'));
resolve();
}).catch(function() {
console.log(colors.red('ERROR LOG 2'));
reject();
});
console.log('LOG 3');
});
} else {
reject(new Error("failed condition"))
}
});
})
});
Promise.all(filePromise).then(function() {
console.log(colors.green('LOG 4'));
});
This does not fix the ordering of your console logs. That is a separate issue. Your console logs are not actually out of order, they are logging as expected. However, this is due to the async call you are making to db.query
which, when triggered does not block waiting for a response. Instead the next line is executed immediately after the function call returns.
Side note: Make sure to handle your err
arguments passed to the inline callback functions of fs.lstat
and fs.readFile
. Failure to do so will result in the promise never completing in the event of an error.
Upvotes: 1