blob: 621a73775591774eb531aa896157e19775e9cc61 [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
19import kotlin.coroutines.experimental.ContinuationInterceptor
20import kotlin.coroutines.experimental.CoroutineContext
21import kotlin.js.Promise
22
23/**
24 * Starts new coroutine and returns its result as an implementation of [Promise].
25 *
26 * The [context] for the new coroutine can be explicitly specified.
27 * See [CoroutineDispatcher] for the standard context implementations that are provided by `kotlinx.coroutines`.
28 * The [context][CoroutineScope.coroutineContext] of the parent coroutine from its [scope][CoroutineScope] may be used,
29 * 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).
40 * @param block the coroutine code.
41 */
42public fun <T> promise(
43 context: CoroutineContext = DefaultDispatcher,
44 start: CoroutineStart = CoroutineStart.DEFAULT,
45 parent: Job? = null,
46 block: suspend CoroutineScope.() -> T
47): Promise<T> =
48 async(context, start, parent, block).asPromise()
49
50/**
51 * Converts this deferred value to the instance of [Promise].
52 */
53public fun <T> Deferred<T>.asPromise(): Promise<T> {
54 val promise = Promise<T> { resolve, reject ->
55 invokeOnCompletion {
56 val e = getCompletionExceptionOrNull()
57 if (e != null) {
58 reject(e)
59 } else {
60 resolve(getCompleted())
61 }
62 }
63 }
64 promise.asDynamic().deferred = this
65 return promise
66}
67
68/**
69 * Converts this promise value to the instance of [Deferred].
70 */
71public fun <T> Promise<T>.asDeferred(): Deferred<T> {
72 val deferred = asDynamic().deferred
73 @Suppress("UnsafeCastFromDynamic")
Roman Elizarov03a266a2018-01-11 10:34:46 +030074 return deferred ?: async(start = CoroutineStart.UNDISPATCHED) { await() }
Roman Elizarovb1708192017-12-22 12:14:05 +030075}
76
77/**
78 * Awaits for completion of the promise without blocking.
79 *
80 * This suspending function is cancellable.
81 * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
82 * stops waiting for the promise and immediately resumes with [CancellationException].
83 */
84public suspend fun <T> Promise<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
85 this@await.then(
86 onFulfilled = { cont.resume(it) },
87 onRejected = { cont.resumeWithException(it) })
88}