包含api的Scala 2期货称为竞争条件

unl*_*hed 1 api scala playframework

我已经在Futures中定义了一些API调用,这些调用可以调用Mashery和Stripe的API

 val stripeFuture = Future { // api call }
 val masheryFuture = Future { //api call }
Run Code Online (Sandbox Code Playgroud)

对于stripeFuture - 主要逻辑是在onSuccess块中的Client对象上设置stripeCustomerId

  stripeFuture onSuccess {
       //client.stripeCustomerId
  }
Run Code Online (Sandbox Code Playgroud)

我已经完成了一个类似于Futures和Promises中的示例的API调用

  val apiCalls = for {

      masheryInfo <- masheryFuture
      stripeCustomer <- stripeFuture
    }
Run Code Online (Sandbox Code Playgroud)

如果其中一个API调用失败,则会回滚

  apiCalls onFailure {
      case pse: MasheryException => {
        // delete stripe customer id
   }

   case e: StripeException => {
       //delete mashery api key
   }
Run Code Online (Sandbox Code Playgroud)

问题是当对Mashery的调用失败'masheryFuture'时,我想从Client对象回滚'获取条带id'但是有一个大约1秒的延迟直到该调用结束并且它没有设置stripeCustomerId直到它命中onSuccess块,因此在ase pse:MasheryException => {}块中,client.getstripeCustomerId返回null.

有没有办法绕过这两个API调用的竞争条件

som*_*ytt 5

使用Future.andThen.

文件:

将副作用函数应用于此未来的结果,并返回具有此未来结果的新未来.

此方法允许强制执行以指定顺序执行回调.

for (f <- Future(x).andThen { y }) 等等

更新:

for (f <- Future(x) andThen {
    case Success(x) => use(x)
    case _ => // ignore
  }) yield result
Run Code Online (Sandbox Code Playgroud)