Promise handler that returns promise


#1

Hello. I am trying to do an Ajax request and handle response via the following code.

window.fetch("/resources.json")
  .then({ res: Response -> res.json() })
  .then({json: Json ->
     // do something
     console.log(json)
  });

I am using Fetch API that returns Promise object.

The code above fails the typecheck at the second then handler with the following reason

Type mismatch

Required: (Promise<Any?>) -> Unit
Found: (Json) -> Unit

Kotlin thinks that the result of previous call is passed into second function without changes. But this is not true. If the result of promise handler is another promise, it will be awaited and next handler will receive unwrapped value, but not the promise itself.

In other words, if res.json() returns Promise<Json> then next handler receives simple Json, without Promise<> wrapper around.

Is there a way how I can make it work? Currently my code refuses to compile, however it should work, as well as it works in native Javascript


#2

What version of Kotlin/JS did you try? Please, try latest (1.2-RC) and tell whether your code still is not compiled.


#3

I am using version 1.1.51 installed via NPM: https://www.npmjs.com/package/kotlin-compiler

How can I replace it with latest? As I understand RC means, that the version hasn’t been published yet.


#4

If it’s possible for you migrate build to Gradle, you can use version from bintray. For example, this blogpost gives instructions how to try 1.2-beta


#5

It’s published as a prerelease version and since it’s not released yet it’s not marked by the latest tag. But you can install by providing exact version 1.2.0-rc-39 in package.json or in terminal command, like: npm install kotlin-compiler@1.2.0-rc-39.


#6

@just-boris do you use it through create-react-kotlin-app?


#7

do you use it through create-react-kotlin-app?

Yes, I do. I managed to use RC version of Kotlin to compile, but I still have the same result. Build from the console fails, IDEA also shows syntax errors.

Also it seems that IDEA always uses built-in Kotlin library to provide type hinting. According to Project Structure -> Libraries content, it picks up library from /Users/my-name/Libraries/Application Support/IdeaIC2017.2/Kotlin/kotlinc/lib/kotlin-stdlib-js-sources.jar which is still 1.1.51


#8

Your example still doesn’t work becouse we have another issue.
You can workaround it by adding explicit cast:
.then({ res: Response -> res.json() as Json })
or by changing type in the lambda:
.then({json: Any? ->
or even:
.then({json: dynamic ->