本文整理汇总了Scala中scala.concurrent.Promise类的典型用法代码示例。如果您正苦于以下问题:Scala Promise类的具体用法?Scala Promise怎么用?Scala Promise使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Promise类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: FutureUtils
//设置package包名称以及导入依赖的类
package util
import java.util.concurrent.Executor
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Try
object FutureUtils {
import com.google.common.util.concurrent.{ListenableFuture => GuavaFuture}
def toFuture[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[T] = {
val pr = Promise[T]()
f.addListener(new Runnable {
def run() = pr.complete(Try(f.get()))
}, executor match {
case e: Executor => e
case _ => new ExecutionContextExecutor(executor)
})
pr.future
}
def toFutureUnit[T](f: GuavaFuture[T])(implicit executor: ExecutionContext): Future[Unit] = {
val pr = Promise[Unit]()
f.addListener(new Runnable {
def run() = pr.complete(Try(f.get()))
}, executor match {
case e: Executor => e
case _ => new ExecutionContextExecutor(executor)
})
pr.future
}
private class ExecutionContextExecutor(executonContext: ExecutionContext) extends java.util.concurrent.Executor {
def execute(command: Runnable): Unit = executonContext.execute(command)
}
}
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:42,代码来源:FutureUtils.scala
示例2: NanoboardPow
//设置package包名称以及导入依赖的类
package com.karasiq.nanoboard.captcha
import java.util.concurrent.{Executors, RejectedExecutionException}
import akka.util.ByteString
import com.karasiq.nanoboard.NanoboardMessage
import com.karasiq.nanoboard.encoding.NanoboardCrypto.{BCDigestOps, sha256}
import com.typesafe.config.{Config, ConfigFactory}
import org.bouncycastle.crypto.digests.SHA256Digest
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Random
object NanoboardPow {
def calculate(message: ByteString): Future[ByteString] = {
val preHashed = sha256.updated(message)
val result = Promise[ByteString]
def submitTasks(): Unit = {
try {
Future.sequence(for (_ ? 0 to 100) yield Future {
val array = Array.ofDim[Byte](NanoboardMessage.POW_LENGTH)
Random.nextBytes(array)
val data = ByteString(array)
if (verify(data, new SHA256Digest(preHashed))) {
result.success(data)
}
}).foreach { _ ?
if (!result.isCompleted) {
submitTasks()
}
}
} catch {
case _: RejectedExecutionException ?
// Pass
case e: Throwable ?
result.failure(e)
}
}
submitTasks()
result.future
}
}
开发者ID:Karasiq,项目名称:nanoboard,代码行数:47,代码来源:NanoboardPow.scala
示例3: TcpAssociationHandle
//设置package包名称以及导入依赖的类
package akka.remote.transport.netty
import akka.actor.Address
import akka.remote.transport.AssociationHandle
import akka.remote.transport.AssociationHandle.{ HandleEvent, HandleEventListener, Disassociated, InboundPayload }
import akka.remote.transport.Transport.AssociationEventListener
import akka.util.ByteString
import java.net.InetSocketAddress
import org.jboss.netty.buffer.{ ChannelBuffers, ChannelBuffer }
import org.jboss.netty.channel._
import scala.concurrent.{ Future, Promise }
import scala.util.{ Success, Failure }
private[remote] class TcpAssociationHandle(val localAddress: Address,
val remoteAddress: Address,
val transport: NettyTransport,
private val channel: Channel)
extends AssociationHandle {
import transport.executionContext
override val readHandlerPromise: Promise[HandleEventListener] = Promise()
override def write(payload: ByteString): Boolean =
if (channel.isWritable && channel.isOpen) {
channel.write(ChannelBuffers.wrappedBuffer(payload.asByteBuffer))
true
} else false
override def disassociate(): Unit = NettyTransport.gracefulClose(channel)
}
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:32,代码来源:TcpSupport.scala
示例4: BlockingIO
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.util
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.{Executors, ThreadFactory}
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future, Promise, blocking}
import scala.util.control.NonFatal
import monix.execution.Scheduler
// https://github.com/alexandru/scala-best-practices/blob/master/sections/4-concurrency-parallelism.md
object BlockingIO {
private val ioThreadPool = Scheduler.io(name = "io-thread")
def future[T](t: => T): Future[T] = {
val p = Promise[T]()
val runnable = new Runnable {
def run() = try {
p.success(blocking(t))
} catch {
case NonFatal(ex) => p.failure(ex)
}
}
ioThreadPool.execute(runnable)
p.future
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:29,代码来源:BlockingIO.scala
示例5: GuavaFutures
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.cassandra
import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture}
import scala.concurrent.{Future, Promise}
private[cassandra] object GuavaFutures {
implicit final class GuavaFutureOpts[A](val guavaFut: ListenableFuture[A]) extends AnyVal {
def asScala(): Future[A] = {
val p = Promise[A]()
val callback = new FutureCallback[A] {
override def onSuccess(a: A): Unit = p.success(a)
override def onFailure(err: Throwable): Unit = p.failure(err)
}
Futures.addCallback(guavaFut, callback)
p.future
}
}
}
开发者ID:akka,项目名称:alpakka,代码行数:20,代码来源:GuavaFutures.scala
示例6: Helpers
//设置package包名称以及导入依赖的类
package com.github.mmolimar.vkitm.utils
import java.util.Properties
import java.util.concurrent.{CancellationException, TimeUnit, Future => JFuture}
import com.typesafe.config.Config
import org.jboss.netty.util.{HashedWheelTimer, Timeout, TimerTask}
import scala.concurrent.{Future, Promise}
import scala.util.Try
object Helpers {
private val pollIntervalMs = 50L
private val timer = new HashedWheelTimer(pollIntervalMs, TimeUnit.MILLISECONDS)
implicit class JFutureHelpers[T](jf: JFuture[T]) {
def asScala: Future[T] = {
val promise = Promise[T]()
def checkCompletion(): Unit = {
if (jf.isCancelled) {
promise.failure(new CancellationException())
} else if (jf.isDone) {
promise.complete(Try(jf.get))
} else {
scheduleTimeout()
}
()
}
def scheduleTimeout(): Unit = {
timer.newTimeout(new TimerTask {
override def run(timeout: Timeout): Unit = checkCompletion()
}, pollIntervalMs, TimeUnit.MILLISECONDS)
()
}
checkCompletion()
promise.future
}
}
implicit def propsFromConfig(config: Config): Properties = {
import scala.collection.JavaConversions._
val props = new Properties()
val map: Map[String, Object] = config.entrySet().map({ entry =>
entry.getKey -> entry.getValue.unwrapped()
})(collection.breakOut)
props.putAll(map)
props
}
}
开发者ID:mmolimar,项目名称:vkitm,代码行数:58,代码来源:Helpers.scala
示例7: Parallel_fibo
//设置package包名称以及导入依赖的类
import scala.concurrent.{Await, Future, Promise}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
object Parallel_fibo
{
def fibonacci(n: Int): Int =
if (n < 2) 1
else fibonacci(n - 1) + fibonacci(n - 2)
def parallel_fibonacci(n: Int): Int =
if (n < 2) 1
else
{
//Future runs algorithms concurrently. It returns at some point. Promise gurantees that it returns.
//Future starts running concurrently when you create it.
val f1 = Future { fibonacci(n - 1) }
val f2 = Future { fibonacci(n - 2) }
//Promise makes sure the result is returned.
val sum = Promise[Int]
f1 onSuccess {
case a =>
f2 onSuccess {
case b =>
//If both of the cases are successful. Compute the sum.
sum.success(a + b)
}
}
//Await the result. Duration is infinite
Await.result(sum.future, Duration.Inf)
}
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
def main(args: Array[String]): Unit = {
val res = time {(parallel_fibonacci(10))}
println(res)
val runtime = Runtime.getRuntime
println("** Used Memory in Parallel_fibo.scala: " + (runtime.totalMemory - runtime.freeMemory))
}
}
开发者ID:vinzee,项目名称:language_comparison,代码行数:52,代码来源:Parallel_fibo.scala
示例8: Last
//设置package包名称以及导入依赖的类
package knot.core.collectors
import knot.core.Collector
import scala.concurrent.{Future, Promise}
case class Last[T]() extends Collector[T, Future[T]] {
private[this] var prev: T = null.asInstanceOf[T]
private[this] val promise: Promise[T] = Promise()
override def collect(): Future[T] = promise.future
override def onUpstreamComplete(): Unit = {
val result = prev
prev = null.asInstanceOf[T]
promise.trySuccess(result)
context.complete()
}
override def onUpstreamError(cause: Throwable): Unit = {
prev = null.asInstanceOf[T]
promise.tryFailure(cause)
context.error(cause)
}
override def onNext(element: T): Unit = {
prev = element
}
}
开发者ID:defvar,项目名称:knot,代码行数:31,代码来源:Last.scala
示例9: RecursiveLeastSquaresStage
//设置package包名称以及导入依赖的类
package pl.gosub.akka.online.recursive.least.squares
import akka.Done
import akka.stream._
import akka.stream.stage._
import scala.concurrent.{Future, Promise}
class RecursiveLeastSquaresStage(val rls: RecursiveLeastSquresFilter)
extends GraphStageWithMaterializedValue[FanInShape2[Double, Double, Double], Future[Done]] {
// Stage syntax
val dataIn: Inlet[Double] = Inlet("RecursiveLeastSquaresStage.dataIn")
val resultsIn: Inlet[Double] = Inlet("RecursiveLeastSquaresStage.resultsIn")
val predictionsOut: Outlet[Double] = Outlet("RecursiveLeastSquaresStage.predictionsOut")
override val shape: FanInShape2[Double, Double, Double] = new FanInShape2(dataIn, resultsIn, predictionsOut)
// Stage semantics
override def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = {
// Completion notification
val p: Promise[Done] = Promise()
val logic = new GraphStageLogic(shape) {
setHandler(resultsIn, new InHandler {
@scala.throws[Exception](classOf[Exception])
override def onPush(): Unit = {
val nextResult = grab(resultsIn)
read(dataIn)({ x =>
if (isAvailable(predictionsOut)) push(predictionsOut, rls.predict(x, nextResult))
}, () => {})
}
})
setHandler(dataIn, new InHandler {
override def onPush(): Unit = {
val x = grab(dataIn)
read(resultsIn)({previousResult =>
if (isAvailable(predictionsOut)) push(predictionsOut, rls.predict(x, previousResult))
}, () => {})
}
override def onUpstreamFinish(): Unit = {
completeStage()
}
})
setHandler(predictionsOut, new OutHandler {
override def onPull(): Unit = {
pull(dataIn)
}
})
}
(logic, p.future)
}
}
开发者ID:gosubpl,项目名称:akka-online,代码行数:59,代码来源:RecursiveLeastSquaresStage.scala
示例10: FollowTheLeaderStage
//设置package包名称以及导入依赖的类
package pl.gosub.akka.online.follow.the.leader
import akka.Done
import akka.stream.stage.{GraphStageLogic, GraphStageWithMaterializedValue, InHandler, OutHandler}
import akka.stream.{Attributes, FanInShape2, Inlet, Outlet}
import scala.concurrent.{Future, Promise}
class FollowTheLeaderStage(private val ftl: FollowTheLeaderLogic) extends GraphStageWithMaterializedValue[FanInShape2[Double, Double, Double], Future[Done]]{
// Stage syntax
val dataIn: Inlet[Double] = Inlet("FollowTheLeaderStage.dataIn")
val resultsIn: Inlet[Double] = Inlet("FollowTheLeaderStage.resultsIn")
val predictionsOut: Outlet[Double] = Outlet("FollowTheLeaderStage.predictionsOut")
override val shape: FanInShape2[Double, Double, Double] = new FanInShape2(dataIn, resultsIn, predictionsOut)
@scala.throws[Exception](classOf[Exception])
override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[Done]) = {
// Completion notification
val p: Promise[Done] = Promise()
val logic = new GraphStageLogic(shape) {
setHandler(resultsIn, new InHandler {
@scala.throws[Exception](classOf[Exception])
override def onPush(): Unit = {
val nextResult = grab(resultsIn)
read(dataIn)({ x =>
if (isAvailable(predictionsOut)) push(predictionsOut, ftl.predict(x, nextResult))
}, () => {})
}
})
setHandler(dataIn, new InHandler {
override def onPush(): Unit = {
val x = grab(dataIn)
read(resultsIn)({previousResult =>
if (isAvailable(predictionsOut)) push(predictionsOut, ftl.predict(x, previousResult))
}, () => {})
}
override def onUpstreamFinish(): Unit = {
completeStage()
}
})
setHandler(predictionsOut, new OutHandler {
override def onPull(): Unit = {
pull(dataIn)
}
})
}
(logic, p.future)
}
}
开发者ID:gosubpl,项目名称:akka-online,代码行数:59,代码来源:FollowTheLeaderStage.scala
示例11: CasbahJournal
//设置package包名称以及导入依赖的类
package akka.persistence.mongo.journal
import akka.actor.{ActorSystem, ActorLogging}
import akka.persistence._
import akka.persistence.journal.AsyncWriteJournal
import com.mongodb.casbah.Imports._
import com.typesafe.config.Config
import scala.collection.immutable
import scala.concurrent.{Promise, Future}
import scala.util.{Failure, Success, Try}
private[journal] class CasbahJournal extends AsyncWriteJournal
with CasbahJournalRoot
with CasbahRecovery
with ActorLogging {
import CasbahJournalRoot._
override val actorSystem: ActorSystem = context.system
override val config: Config = context.system.settings.config.getConfig(configRootKey)
implicit val concern: WriteConcern = writeConcern
implicit val rejectNonSerializableObjects: Boolean = rejectNonSerializableObjectId
initialize()
def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = {
val messagesToTryAndPersist: immutable.Seq[Try[DBObject]] = messages.flatMap(message =>
message.payload.map(persistentReprToDBObject))
val persistedMessages: Future[WriteResult] =
Future(persistExecute(mongoCollection, messagesToTryAndPersist.flatMap(_.toOption)))
val promise = Promise[immutable.Seq[Try[Unit]]]()
persistedMessages.onComplete {
case Success(_) if messagesToTryAndPersist.exists(_.isFailure) =>
promise.success(messagesToTryAndPersist.map(_ match {
case Success(_) => Success((): Unit)
case Failure(error) => Failure(error)
}))
case Success(_) =>
promise.complete(Success(Nil))
case Failure(e) => promise.failure(e)
}
promise.future
}
def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = {
Future(deleteTo(mongoCollection, concern, persistenceId, toSequenceNr))
}
override def postStop(): Unit = {
shutdown()
}
}
开发者ID:asrulsibaoel,项目名称:akka-mongo,代码行数:62,代码来源:CasbahJournal.scala
示例12: KillServiceDelegate
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package core.task.termination.impl
import akka.Done
import akka.actor.ActorRef
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.core.task.termination.{ KillReason, KillService }
import org.slf4j.LoggerFactory
import scala.concurrent.{ Future, Promise }
import scala.collection.immutable.Seq
private[termination] class KillServiceDelegate(actorRef: ActorRef) extends KillService {
import KillServiceDelegate.log
import KillServiceActor._
override def killInstances(instances: Seq[Instance], reason: KillReason): Future[Done] = {
log.info(
s"Killing ${instances.size} tasks for reason: $reason (ids: {} ...)",
instances.take(3).map(_.instanceId).mkString(","))
val promise = Promise[Done]
actorRef ! KillInstances(instances, promise)
promise.future
}
override def killInstance(instance: Instance, reason: KillReason): Future[Done] = {
killInstances(Seq(instance), reason)
}
override def killUnknownTask(taskId: Task.Id, reason: KillReason): Unit = {
log.info(s"Killing unknown task for reason: $reason (id: {})", taskId)
actorRef ! KillUnknownTaskById(taskId)
}
}
object KillServiceDelegate {
private[impl] val log = LoggerFactory.getLogger(getClass)
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:42,代码来源:KillServiceDelegate.scala
示例13: CollectionStage
//设置package包名称以及导入依赖的类
package mesosphere.marathon.stream
import akka.stream.{ Attributes, Inlet, SinkShape }
import akka.stream.stage.{ GraphStageLogic, GraphStageWithMaterializedValue, InHandler }
import scala.collection.mutable
import scala.concurrent.{ Future, Promise }
private final class CollectionStage[T, C](buf: mutable.Builder[T, C])
extends GraphStageWithMaterializedValue[SinkShape[T], Future[C]] {
val in = Inlet[T]("collection.in")
override def toString: String = "collectionStage"
override val shape: SinkShape[T] = SinkShape.of(in)
override protected def initialAttributes: Attributes = Attributes.name("setSink")
override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Future[C]) = {
val promise = Promise[C]()
val logic = new GraphStageLogic(shape) {
override def preStart(): Unit = pull(in)
setHandler(in, new InHandler {
override def onPush(): Unit = {
buf += grab(in)
pull(in)
}
override def onUpstreamFinish(): Unit = {
promise.trySuccess(buf.result())
completeStage()
}
override def onUpstreamFailure(ex: Throwable): Unit = {
promise.tryFailure(ex)
failStage(ex)
}
})
}
(logic, promise.future)
}
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:46,代码来源:CollectionStage.scala
示例14: StopActor
//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade
import akka.actor.{ ActorLogging, Terminated, Actor, ActorRef }
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import scala.concurrent.Promise
class StopActor(toStop: ActorRef, promise: Promise[Boolean], reason: Throwable) extends Actor with ActorLogging {
override def preStart(): Unit = {
context.watch(toStop)
toStop ! Cancel(reason)
}
def receive: Receive = {
case Terminated(`toStop`) =>
promise.success(true)
log.debug(s"$toStop has successfully been stopped.")
context.unwatch(toStop)
context.stop(self)
}
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:22,代码来源:StopActor.scala
示例15: StopActorTest
//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade
import akka.actor.{ ActorRef, Props }
import akka.testkit.TestActor.{ AutoPilot, NoAutoPilot }
import akka.testkit.TestProbe
import mesosphere.marathon.test.MarathonActorSupport
import mesosphere.marathon.upgrade.DeploymentActor.Cancel
import org.scalatest.{ FunSuiteLike, Matchers }
import scala.concurrent.duration._
import scala.concurrent.{ Await, Promise }
class StopActorTest extends MarathonActorSupport with FunSuiteLike with Matchers {
test("Stop") {
val promise = Promise[Boolean]()
val probe = TestProbe()
probe.setAutoPilot(new AutoPilot {
def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
case Cancel(reason) =>
system.stop(probe.ref)
NoAutoPilot
}
})
val ref = system.actorOf(Props(classOf[StopActor], probe.ref, promise, new Exception))
watch(ref)
expectTerminated(ref)
Await.result(promise.future, 5.seconds) should be(true)
}
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:34,代码来源:StopActorTest.scala
示例16: message
//设置package包名称以及导入依赖的类
package controllers
import akka.actor.ActorSystem
import javax.inject._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.concurrent.duration._
def message = Action.async {
getFutureMessage(1.second).map { msg =>
Ok(msg)
}
}
private def getFutureMessage(delayTime: FiniteDuration): Future[String] = {
val promise: Promise[String] = Promise[String]()
actorSystem.scheduler.scheduleOnce(delayTime) { promise.success("Hi!"); () }(actorSystem.dispatcher)
promise.future
}
}
开发者ID:digital-wonderland,项目名称:play-webpack-typescript-react,代码行数:23,代码来源:AsyncController.scala
示例17: ImperativeRequestContext
//设置package包名称以及导入依赖的类
package org.cristal.api.helper
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise
final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
private implicit val ec = ctx.executionContext
def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}
trait ApiHelper {
def notImplementedResponse(msg: String = ""): StandardRoute =
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
s"<h1>We plan to support this resource soon.</h1>"))
def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
val p = Promise[RouteResult]()
inner(new ImperativeRequestContext(ctx, p))
p.future
}
}
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala
示例18: findOneOrCreate
//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
package object mongo {
def findOneOrCreate(collection: BSONCollection)
(userQuery: BSONDocument, getNewDoc: => Future[MongoUser]): Future[MongoUser] = {
implicit def mongoEntityWriter: BSONDocumentWriter[MongoEntity] = Macros.writer[MongoEntity]
implicit def mongoThoughtWriter: BSONDocumentWriter[MongoThought] = Macros.writer[MongoThought]
implicit def mongoMessageWriter: BSONDocumentWriter[MongoMessage] = Macros.writer[MongoMessage]
implicit def mongoUserWriter: BSONDocumentWriter[MongoUser] = Macros.writer[MongoUser]
implicit def mongoEntityReader: BSONDocumentReader[MongoEntity] = Macros.reader[MongoEntity]
implicit def mongoThoughtReader: BSONDocumentReader[MongoThought] = Macros.reader[MongoThought]
implicit def mongoMessageReader: BSONDocumentReader[MongoMessage] = Macros.reader[MongoMessage]
implicit def mongoUserReader: BSONDocumentReader[MongoUser] = Macros.reader[MongoUser]
val p = Promise[MongoUser]()
collection.find(userQuery).one[MongoUser].onComplete {
case Success(docOpt) =>
if (docOpt.isDefined) {
p.complete(Try(docOpt.get))
} else {
getNewDoc.onComplete {
case Success(newDocOpt) =>
collection.insert(newDocOpt).onComplete { r =>
collection.find(userQuery).one[MongoUser]
.onComplete {
case Success(docOpt2) =>
val mongoUser = docOpt2.get
p.complete(Try(mongoUser))
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
p.future
}
}
开发者ID:aluxian,项目名称:SusuCatBot,代码行数:50,代码来源:package.scala
示例19: RichFuture
//设置package包名称以及导入依赖的类
package swave.core.util
import java.util.concurrent.TimeoutException
import scala.concurrent.duration._
import scala.concurrent.{Await, Future, Promise}
import swave.core.StreamEnv
final class RichFuture[T](val underlying: Future[T]) extends AnyVal {
def await(timeout: FiniteDuration = 1.second): T =
underlying.value match {
case Some(t) ? t.get
case None if timeout == Duration.Zero ? throw new TimeoutException(s"Future was not completed")
case _ ? Await.result(underlying, timeout)
}
def delay(duration: FiniteDuration)(implicit env: StreamEnv): Future[T] = {
import env.defaultDispatcher
val promise = Promise[T]()
underlying.onComplete { value ?
env.scheduler.scheduleOnce(duration) { promise.complete(value); () }
}
promise.future
}
}
开发者ID:sirthias,项目名称:swave,代码行数:26,代码来源:RichFuture.scala
示例20: fixtureState
//设置package包名称以及导入依赖的类
package swave.core.internal.testkit
import scala.collection.immutable.VectorBuilder
import scala.concurrent.{Future, Promise}
import swave.core.impl.stages.StageImpl
private[testkit] trait TestStage extends StageImpl {
private[this] val resultBuilder = new VectorBuilder[AnyRef]
private[this] var _resultSize = 0
private[this] var _fixtureState: TestFixture.State = TestFixture.State.Starting
private[this] val _finishedState = Promise[TestFixture.State.Finished]()
private[this] var onElem: AnyRef ? Unit = x ? ()
def fixtureState: TestFixture.State = _fixtureState
def fixtureState_=(value: TestFixture.State): Unit = {
value match {
case TestFixture.State.Cancelled ? _finishedState.success(TestFixture.State.Cancelled)
case TestFixture.State.Completed ? _finishedState.success(TestFixture.State.Completed)
case TestFixture.State.Error(e) ? _finishedState.failure(e)
case _ ?
}
_fixtureState = value
}
def finishedState: Future[TestFixture.State.Finished] = _finishedState.future
private[testkit] final def result[T]: Vector[T] = resultBuilder.result().asInstanceOf[Vector[T]]
private[testkit] final def resultSize: Int = _resultSize
protected final def recordElem(elem: AnyRef): Unit = {
resultBuilder += elem
_resultSize += 1
onElem(elem)
}
def appendElemHandler(f: AnyRef ? Unit): Unit = {
val prev = onElem
onElem = { elem ?
prev(elem)
f(elem)
}
}
def id: Int
def formatLong: String
def scriptedSize: Int
}
开发者ID:sirthias,项目名称:swave,代码行数:52,代码来源:TestStage.scala
注:本文中的scala.concurrent.Promise类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论