用期货过滤内部的理解

时间:2016-07-06 10:53:20

标签: scala future for-comprehension

我正在做这样的事情:

<div id="moving_to_2perf">
DA
<p> paragraph</p>
</div>

<style type="text/css">  
#moving_to_2perf{
  color: red;
};     
</style>  

<script type='text/javascript'>

  function getCookie(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for(var i = 0; i <ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') {
              c = c.substring(1);
          }
          if (c.indexOf(name) == 0) {
              return c.substring(name.length,c.length);
          }
      }
      return "";
  }

  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  }

  $( document ).ready(function() {
    console.log('salut1');
    insert_text();
  });

  cookie = getCookie('2parale_to_2performant_cokie');
  if (!cookie) {
    insert_text2();
  };

  function insert_text(){
    console.log('salut2');
    var para = document.createElement("p");
    var node = document.createTextNode("This is new.");
    para.appendChild(node);

    var element = document.getElementById("moving_to_2perf");
    element.appendChild(para);
  };

  function insert_text2(){
    console.log('salut3');
    $("#moving_to_2perf").html("Hello World");
    $("#moving_to_2perf").append('<p id="testp"> TEST </p>');

    console.log($('#testp').position());
    console.log($('#testp').offset());
  };


</script>

当不满足过滤器时,它会跳过剩下的两个步骤(好!),抛出一个异常(不好),我必须抓住并在最后处理。使用流控制的异常对我来说并不太优雅,我想知道是否有更好的方法来做到这一点,除了显而易见的 - 用if语句包装所有剩余的行:

 (for { 
   data <- Future(getData)
   updated = makeChanges(data) if updated != data
   _ <- Future(saveUpdates(updated))
   _ <- Future(recordTransaction)
 } yield ()).recover { case e: NoSuchElementException => () }

1 个答案:

答案 0 :(得分:3)

我不认为你可以通过这种方式避免使用for comprehension的流控制的异常,你可以使用嵌套表达式代替过滤器并手动处理条件,为scala提供它需要的返回类型条件不满意:

for {
  data <- Future(data)
  updated = makeChanges(data)
  res = {
    if (updated != data) Future.successful(())
    else for {
      _ <- Future(saveUpdates(updated))
      _ <- Future(recordTransaction)
    } yield ()
  }
} yield res

但是对于这个例子,我会采用简单的方法并删除for comprehension,从而产生更易读的代码(可能你的真实用例虽然更复杂):

Future(data).flatMap(d => {
  val updated = makeChanges(d)
  if(updated == d) Future.successful(())
  else Future(saveUpdates(updated)).map(_ => recordTransaction)
})