blob: 5e12cba7135b62b07142ddad804bf4c4f388edaa [file] [log] [blame]
Roman Elizarovb1708192017-12-22 12:14:05 +03001/*
2 * Copyright 2016-2017 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package kotlinx.coroutines.experimental
18
Roman Elizarova4b56932018-03-13 17:59:48 +030019import kotlin.coroutines.experimental.*
20import kotlin.js.*
Roman Elizarovb1708192017-12-22 12:14:05 +030021
22/**
23 * Starts new coroutine and returns its result as an implementation of [Promise].
24 *
25 * The [context] for the new coroutine can be explicitly specified.
26 * See [CoroutineDispatcher] for the standard context implementations that are provided by `kotlinx.coroutines`.
Roman Elizarov9fe5f462018-02-21 19:05:52 +030027 * The [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/coroutine-context.html)
28 * of the parent coroutine may be used,
Roman Elizarovb1708192017-12-22 12:14:05 +030029 * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine.
30 * The parent job may be also explicitly specified using [parent] parameter.
31 *
32 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [DefaultDispatcher] is used.
33 *
34 * By default, the coroutine is immediately scheduled for execution.
35 * Other options can be specified via `start` parameter. See [CoroutineStart] for details.
36 *
37 * @param context context of the coroutine. The default value is [DefaultDispatcher].
38 * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT].
39 * @param parent explicitly specifies the parent job, overrides job from the [context] (if any).
Roman Elizarova4b56932018-03-13 17:59:48 +030040 * @param onCompletion optional completion handler for the coroutine (see [Job.invokeOnCompletion]).
Roman Elizarovb1708192017-12-22 12:14:05 +030041 * @param block the coroutine code.
42 */
43public fun <T> promise(
44 context: CoroutineContext = DefaultDispatcher,
45 start: CoroutineStart = CoroutineStart.DEFAULT,
46 parent: Job? = null,
Roman Elizarova4b56932018-03-13 17:59:48 +030047 onCompletion: CompletionHandler? = null,
Roman Elizarovb1708192017-12-22 12:14:05 +030048 block: suspend CoroutineScope.() -> T
49): Promise<T> =
Roman Elizarova4b56932018-03-13 17:59:48 +030050 async(context, start, parent, onCompletion, block = block).asPromise()
Roman Elizarovb1708192017-12-22 12:14:05 +030051
52/**
53 * Converts this deferred value to the instance of [Promise].
54 */
55public fun <T> Deferred<T>.asPromise(): Promise<T> {
56 val promise = Promise<T> { resolve, reject ->
57 invokeOnCompletion {
58 val e = getCompletionExceptionOrNull()
59 if (e != null) {
60 reject(e)
61 } else {
62 resolve(getCompleted())
63 }
64 }
65 }
66 promise.asDynamic().deferred = this
67 return promise
68}
69
70/**
71 * Converts this promise value to the instance of [Deferred].
72 */
73public fun <T> Promise<T>.asDeferred(): Deferred<T> {
74 val deferred = asDynamic().deferred
75 @Suppress("UnsafeCastFromDynamic")
Roman Elizarov03a266a2018-01-11 10:34:46 +030076 return deferred ?: async(start = CoroutineStart.UNDISPATCHED) { await() }
Roman Elizarovb1708192017-12-22 12:14:05 +030077}
78
79/**
80 * Awaits for completion of the promise without blocking.
81 *
82 * This suspending function is cancellable.
83 * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
84 * stops waiting for the promise and immediately resumes with [CancellationException].
85 */
86public suspend fun <T> Promise<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
87 this@await.then(
88 onFulfilled = { cont.resume(it) },
89 onRejected = { cont.resumeWithException(it) })
90}