gpt4 book ai didi

javascript - 建议练习: make sure a promise needed to be called only if a certain condition happened has resolved before going on

转载 作者:行者123 更新时间:2023-11-28 17:25:38 24 4
gpt4 key购买 nike

我有一个 promise ,其抽象代码如下:

const myPromise = (input) => new Promise((resolve, reject) => {
//does something with input and provide some result
if (everything_is_ok) resolve(result);
else reject(error);
});

这是我的脚本中的过程的抽象流程:

let myVar;
//some code instructions...
myVar = something; //this comes as result of some code
if (condition){
//(once promises resolves) compute function does something with pr_output
//and provides another resulting output that gets stored on myVar for further computation
myPromise(takes myVar or some data as input here).then((pr_output)=>{myVar=compute(pr_output);});
}
//further operations with myVar follow here...
//AND, if condition was true, I want/need to be sure that the promise has resolved
//and the computation in its "then" instruction ended as well before going on...

所以现在的问题是: (如何)是否可以继续而不调用后续函数?我的意思是我知道我可以简单地做类似的事情:

if (condition){
myPromise(takes myVar or some data as input here).then((pr_output)=>{myVar=compute(pr_output);
anotherProcedure(myVar); // <== THIS IS IT
});
} else anotherPocedure(myVar) // <== AND... THIS IS IT TOO

因此,我基本上会将条件检查之后的每个计算放入 anotherProcedure(myVar) 中并调用它(提供 myVar 作为输入):

  • 在promise的then中,如果条件true
  • 或者在else分支中,如果条件

这是我可以采用的唯一方法,还是是否可以避免将进一步的计算包装在另一个过程中并以这种方式调用它?(如果是,请告诉我该怎么做)谢谢

最佳答案

仅创建一个 Promise 链,您可以将 anotherPocedure(myVar) 添加到其末尾。如果条件为 true,则返回 myPromise 调用(从而“暂停”Promise 链直到其解析),否则不返回任何内容(从而运行下一个 .then 立即具有 anotherPocedure)。翻译你的较低代码,它可能看起来像

Promise.resolve()
.then(() => {
if (condition) return myPromise(takes myVar or some data as input here)
.then((pr_output) => {
myVar = compute(pr_output);
});
})
.then(() => anotherPocedure(myVar));

尽管将第一个 .then 提取到自己的函数中会更具可读性,以获得更好的可读性:

const tryCompute = () => {
if (condition) return myPromise(takes myVar or some data as input here)
.then((pr_output) => {
myVar = compute(pr_output);
});
else return Promise.resolve();
};

tryCompute()
.then(() => anotherPocedure(myVar));

关于javascript - 建议练习: make sure a promise needed to be called only if a certain condition happened has resolved before going on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684328/

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