我使用的是帶有Node.js的Inquirer庫,在使用Promise時我仍然得到厄運的金字塔,我做錯了什麼?在使用承諾時,我仍然得到厄運的金字塔,我做錯了什麼?
僅供參考問話庫API基本上是:
inquirer.prompt([
question1,
question2,
question3,
...
questionX
]).then(function(answers){});
其中的答案是散列,與代表每個問題的密鑰。這裏沒有什麼特別的。
總之,使用API,我總是得到getAnswersToPrompts().then(function(answers){})
,它似乎更方便地保持嵌套前一個內部的承諾......像這樣:
function run (rootDir) {
return watchHelper().then(function (answers) {
return chooseDirs({
allowDirs: answers.allow,
originalRootDir: rootDir,
onlyOneFile: false
}).then(function (pathsToRun) {
assert(pathsToRun.length > 0, ' You need to select at least one path.');
return getOptions(availableOptionsForPlainNode).then(function (answers) {
const selectedOpts = answers[ 'command-line-options' ];
return localOrGlobal().then(function (answers) {
const sumanExec = answers.localOrGlobal;
console.log(' => ', colors.magenta.bold([ '$', sumanExec, '--watch', pathsToRun, selectedOpts ].join(' ')));
});
});
});
}).catch(rejectionHandler);
}
我可能做到這一點,而不是:
function run(){
return makePromise()
.then(fn1(data1))
.then(fn2(data2))
.then(fn3(data3))
}
其中FN1,FN2,FN3樣子:
function fnX(data){
return function(answers){
return promise(data);
}
}
但這正m讓事情變得更加複雜AFAICT
只要儘可能清楚,我肯定需要先前承諾的結果,但有時我需要承諾之前的結果,甚至是之前的結果。
嵌套功能允許我需要在範圍內的數據,由於閉包等
使用術語「厄運的金字塔」upvote – imjared
大聲笑我真的不介意嵌套的調用,但只是好奇,如果有一種方法 –
你試過'async'模塊與其'async.waterfall' ?你的情況會更清晰。 – Aruna