I have to read, compile multiple jade files and then use the these files. I'm using bluebird promises library with the below code:
var indexJadeFile = 'template/index.jade';
var otherJadeFile = 'template/other.jade';
function readAndCompileJade(jadeFile){
fs.readFileAsync(jadeFile, 'utf8').then(function(content){
console.log('reading jade file: ' , jadeFile);
return jade.compile(content, {
pretty : true,
filename : jadeFile,
basedir : templateBaseDir
});
})
}
promise.all([
readAndCompileJade(indexJadeFile),
readAndCompileJade(postJadeFile),
readAndCompileJade(sitemapJadeFile),
readAndCompileJade(archivesJadeFile)])
.then(function(results){
console.log('results block');
compiledIndex = results[0];
compiledPost = results[1];
compiledSitemap = results[2];
compiledArchives = results[3];
});
I assumed that then block will be executed after all the jade files are executed. But when I execute, I find that the results block is printed before reading jade file statements.
How do I wait for all promises to be completed and then execute the rest of the block?
That's because your readAndCompileJade is synchronous and does not return a promise.
You have to return a promise.
How should promise.all know when it should continue?
In your case I assume that fs.readFileAsync is promise based as you use .then so you can just return it:
function readAndCompileJade(jadeFile){
return fs.readFileAsync(jadeFile, 'utf8').then(function(content){
console.log('reading jade file: ' , jadeFile);
return jade.compile(content, {
pretty : true,
filename : jadeFile,
basedir : templateBaseDir
});
})
}