在我启动Web服务器之前,我想为配置文件创建一些本地目录,而不是
// 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();
});
});
}
}
但是,控制台打印输出如下所示:
Server is running on port 3000
Created new dir: configs
Created new dir: logs
为什么首先创建目录?不应该Promise.all返回一个只有在完成所有输入承诺后才能满足的新承诺?
答案 0 :(得分:4)
您传递的是调用函数httpPromise.startServer
而不是函数本身的结果:
这应解决问题:
promise.all([fsPromise.createDir('configs'), fsPromise.createDir('logs')])
.then(httpPromise.startServer);
.then
函数将回调函数作为参数。这里的原始承诺无法正确执行。