• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 package kotlinx.coroutines
6 
7 import kotlin.js.*
8 import kotlin.test.*
9 
10 class PromiseTest : TestBase() {
11     @Test
12     fun testPromiseResolvedAsDeferred() = GlobalScope.promise {
13         val promise = Promise<String> { resolve, _ ->
14             resolve("OK")
15         }
16         val deferred = promise.asDeferred()
17         assertEquals("OK", deferred.await())
18     }
19 
20     @Test
21     fun testPromiseRejectedAsDeferred() = GlobalScope.promise {
22         lateinit var promiseReject: (Throwable) -> Unit
23         val promise = Promise<String> { _, reject ->
24             promiseReject = reject
25         }
26         val deferred = promise.asDeferred()
27         // reject after converting to deferred to avoid "Unhandled promise rejection" warnings
28         promiseReject(TestException("Rejected"))
29         try {
30             deferred.await()
31             expectUnreached()
32         } catch (e: Throwable) {
33             assertTrue(e is TestException)
34             assertEquals("Rejected", e.message)
35         }
36     }
37 
38     @Test
39     fun testCompletedDeferredAsPromise() = GlobalScope.promise {
40         val deferred = async(start = CoroutineStart.UNDISPATCHED) {
41             // completed right away
42             "OK"
43         }
44         val promise = deferred.asPromise()
45         assertEquals("OK", promise.await())
46     }
47 
48     @Test
49     fun testWaitForDeferredAsPromise() = GlobalScope.promise {
50         val deferred = async {
51             // will complete later
52             "OK"
53         }
54         val promise = deferred.asPromise()
55         assertEquals("OK", promise.await()) // await yields main thread to deferred coroutine
56     }
57 
58     @Test
59     fun testCancellableAwaitPromise() = GlobalScope.promise {
60         lateinit var r: (String) -> Unit
61         val toAwait = Promise<String> { resolve, _ -> r = resolve }
62         val job = launch(start = CoroutineStart.UNDISPATCHED) {
63             toAwait.await() // suspends
64         }
65         job.cancel() // cancel the job
66         r("fail") // too late, the waiting job was already cancelled
67     }
68 
69     @Test
70     fun testAsPromiseAsDeferred() = GlobalScope.promise {
71         val deferred = async { "OK" }
72         val promise = deferred.asPromise()
73         val d2 = promise.asDeferred()
74         assertSame(d2, deferred)
75         assertEquals("OK", d2.await())
76     }
77 }