Promise: ignoreErrors for collectResults and all

This commit is contained in:
Vladimir Krivosheev
2017-04-05 17:11:34 +02:00
parent 5c440c02db
commit 269ed5682d
2 changed files with 16 additions and 6 deletions
@@ -19,6 +19,7 @@ import com.intellij.testFramework.assertConcurrent
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicInteger
@@ -48,7 +49,7 @@ class AsyncPromiseTest {
val numThreads = 30
assertConcurrent(*Array(numThreads, {
if (it and 1 === 0) r else s
if ((it and 1) == 0) r else s
}))
assertThat(count.get()).isEqualTo(numThreads / 2)
@@ -69,6 +70,13 @@ class AsyncPromiseTest {
})
}
@Test
fun `ignoreErrors`() {
val a = resolvedPromise("foo")
val b = rejectedPromise<String>()
assertThat(collectResults(listOf(a, b), ignoreErrors = true).blockingGet(100, TimeUnit.MILLISECONDS)).containsExactly("foo")
}
@Test
fun blockingGet2() {
val promise = AsyncPromise<String>()
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -116,7 +116,8 @@ inline fun Promise<*>.rejected(node: Obsolescent, crossinline handler: (Throwabl
override fun consume(param: Throwable) = handler(param)
})
fun <T> collectResults(promises: List<Promise<T>>): Promise<List<T>> {
@JvmOverloads
fun <T> collectResults(promises: List<Promise<T>>, ignoreErrors: Boolean = false): Promise<List<T>> {
if (promises.isEmpty()) {
return resolvedPromise(emptyList())
}
@@ -125,7 +126,7 @@ fun <T> collectResults(promises: List<Promise<T>>): Promise<List<T>> {
for (promise in promises) {
promise.done { results.add(it) }
}
return all(promises, results)
return all(promises, results, ignoreErrors)
}
@JvmOverloads
@@ -187,7 +188,8 @@ fun ActionCallback.toPromise(): Promise<Void> {
fun all(promises: Collection<Promise<*>>): Promise<*> = if (promises.size == 1) promises.first() else all(promises, null)
fun <T> all(promises: Collection<Promise<*>>, totalResult: T?): Promise<T> {
@JvmOverloads
fun <T> all(promises: Collection<Promise<*>>, totalResult: T?, ignoreErrors: Boolean = false): Promise<T> {
if (promises.isEmpty()) {
@Suppress("UNCHECKED_CAST")
return DONE as Promise<T>
@@ -195,7 +197,7 @@ fun <T> all(promises: Collection<Promise<*>>, totalResult: T?): Promise<T> {
val totalPromise = AsyncPromise<T>()
val done = CountDownConsumer(promises.size, totalPromise, totalResult)
val rejected = Consumer<Throwable> { error -> totalPromise.setError(error) }
val rejected = if (ignoreErrors) Consumer<Throwable> { done.consume(null) } else Consumer<Throwable> { totalPromise.setError(it) }
for (promise in promises) {
promise.done(done)