我有一个承诺,其抽象代码如下:
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作为输入):如果条件为真,则在诺言的
then
中或在
else
分支(如果条件为假)这是我唯一的方法,还是可以避免不必将进一步的计算包装在另一个过程中并以此方式调用?
(如果是,请告诉我该怎么做)
谢谢
最佳答案
如注释中所建议,您可以简单地使用async / await:
(async function() {
if(condition) {
const myVar = compute( await myPromise());
}
anotherProcedure();
})();