我在使用Commander JS和Promise时遇到了麻烦。我正在创建一个CLI工具,该工具执行一些文件系统操作,这些操作包装在Promise中,并且大部分情况下都在起作用。但是,当我通过诺言添加更多文件系统工作时,我注意到该命令将过早终止。我试图通过使用setTimeout调用模拟工作来简化我的示例,以试图找出我感到困惑的地方。这是我用来演示该问题的代码:
var program = require('commander');
fs = require('fs');
path = require('path');
program
.version('0.0.1')
.command('add [options] <package.json>', 'Adds Tizen commands line build support to an existing Tizen project.').alias('a')
.option('-f, --file [package.json]', 'File which contains the package.json project description')
.option('-c, --config [config]', 'Path to the config.xml where the projectId is read from.')
.option('-p, --projectid [projectid]', 'The project Id to use in the project.')
.action(() => {
console.log('taking action...');
return new Promise((resolve) => {
console.log('setting timeout...');
setTimeout(() => {
console.log('Timeout!');
resolve();
} ,2000);
}
).then(() => console.log('Done'));
})
.parse(process.argv);
console.log('parse completed...');
console.log('running outer promise...');
return new Promise((resolve) => {
console.log('setting timeout...');
setTimeout(() => {
console.log('Timeout!');
resolve();
} ,2000);
}
).then(() => console.log('Done'));
当我运行它时,我得到:
taking action...
setting timeout...
parse completed...
running outer promise...
setting timeout...
Process finished with exit code 0
但是,当我注释如下的解析调用时,它似乎要等待外部承诺:
.action(() => {
console.log('taking action...');
return new Promise((resolve) => {
console.log('setting timeout...');
setTimeout(() => {
console.log('Timeout!');
resolve();
} ,2000);
}
).then(() => console.log('Done'));
})
//.parse(process.argv);
console.log('parse completed...');
console.log('running outer promise...');
return new Promise((resolve) => {
console.log('setting timeout...');
setTimeout(() => {
console.log('Timeout!');
resolve();
} ,2000);
}
).then(() => console.log('Done'));
我在这里得到:
parse completed...
running outer promise...
setting timeout...
Timeout!
Done
Process finished with exit code 0
就好像对解析的调用在内部触发了某种动作,使动作回调完成后程序就可以完成。如何让它等待实际操作完成?