建议做法:确保仅在发生某种情况后解决了才可以进行承诺

时间:2018-08-04 09:38:33

标签: javascript 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作为输入):

  • 如果条件 true
  • ,则在诺言的then
  • ,或者如果 condition false
  • ,则在else分支中

这是我唯一的方法吗?或者是否可以避免将更多的计算包装到另一个过程中并以此方式调用? (如果是,请告诉我该怎么做) 谢谢

2 个答案:

答案 0 :(得分:2)

仅创建一个 Promise链,就可以将anotherPocedure(myVar)固定到其末尾。如果条件为真,则返回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));

答案 1 :(得分:1)

根据评论中的建议,您可以简单地使用async / await:

 (async function() {
    if(condition) {
      const myVar = compute( await myPromise());
    }
    anotherProcedure();
 })();