gpt4 book ai didi

javascript - 使用 promise 时我仍然会遇到厄运金字塔,我做错了什么?

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:53 25 4
gpt4 key购买 nike

我正在使用 Inquirer使用 Node.js 的库,在使用 promise 时我仍然会遇到厄运金字塔,我做错了什么?

仅供引用,查询器库 API 基本上是:

inquirer.prompt([
question1,
question2,
question3,
...
questionX
]).then(function(answers){});

其中 answers 是一个散列,带有代表每个问题的键。这里没有什么特别的地方。

无论如何,使用 API,我总是得到 getAnswersToPrompts().then(function(answers){}) 并且将 promise 嵌套在前一个中似乎更方便......比如所以:

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);

}
}

但这只会让理解 AFAICT 变得更加复杂

尽可能清楚,我确实需要之前 promise 的结果,但有时我需要之前 promise 的结果,甚至需要之前的结果。

由于闭包等,嵌套函数允许我需要的数据在范围内。

最佳答案

返回下一个 Promise before 调用 then:

function run (rootDir) {
var pathsToRun;

return watchHelper()
.then(function (watchHelperAnswers) {
return chooseDirs({
allowDirs: watchHelperAnswers.allow,
originalRootDir: rootDir,
onlyOneFile: false
});
}).then(function (chooseDirsResult) {
assert(chooseDirsResult.length > 0, ' You need to select at least one path.');
pathsToRun = chooseDirsResult;
return getOptions(availableOptionsForPlainNode);
}).then(function (getOptionsAnswers) {
const selectedOpts = getOptionsAnswers[ 'command-line-options' ];
return localOrGlobal();
}).then(function (localOrGlobalAnswers) {
const sumanExec = localOrGlobalAnswers.localOrGlobal;
console.log(' => ', colors.magenta.bold([ '$', sumanExec, '--watch', pathsToRun,
selectedOpts ].join(' ')));
}).catch(rejectionHandler);
}

but sometimes I need the result from the promise prior to that or even the result prior to that

您的示例中的唯一实例是 pathsToRun。我认为嵌套函数两三个深度以容纳它仍然是可读的,但您的另一个选择是在 promise 链之外定义一个变量,我在上面为 pathsToRun 显示了这一点。

最后,您的示例在整个 promise 链中使用了三个不同的变量,它们都称为 answers,这可能会增加困惑。总的来说,我认为对 promise 回调结果使用相同的名称是可以的,但为了清楚起见,我在这里重命名了它们。

关于javascript - 使用 promise 时我仍然会遇到厄运金字塔,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com