user1927638 user1927638 - 1 month ago 5
Node.js Question

Node.js Promises are not being executed in order

Before I start an web server, I'd like to create a few local directories for config files and what not

// app.js
var fsPromise = require('./fs-promise.js');
var httpPromise = require('./http-promise.js');
var promise = require('promise');

promise.all([fsPromise.createDir('configs'), fsPromise.createDir('logs')])
.then(httpPromise.startServer());

// fs-promise.js
var fs = require('fs');
var promise = require('promise');

module.exports = {
...
createDir: function(directory) {
return new promise(function(fulfill, reject) {
//console.log('Creating new dir: ' + directory);
var newDir = __dirname + "\\" + directory;
fs.mkdir(newDir, function(err) {
if (err) {
reject();
}
else {
console.log('Created new dir: ' + directory);
fulfill();
}
});
});
}
}

// http-promise.js
...
module.exports = {
startServer: function() {
return new promise(function(fulfill, reject) {
http.listen(configParams.server_port, function() {
console.log('Server is running on port ' + configParams.server_port);
fulfill();
});
});
}
}


However, the console printout looks something like this:

Server is running on port 3000
Created new dir: configs
Created new dir: logs


Why are the directories being created first? Shouldn't Promise.all return a new promise that is only satisfied when all the input promises are completed?

Answer

You are passing the result of calling the function httpPromise.startServer instead of the function itself:

This should fix the issue:

promise.all([fsPromise.createDir('configs'), fsPromise.createDir('logs')])
  .then(httpPromise.startServer);

The .then function takes a callback function as an argument. A raw promise here cannot be executed correctly.