invariant
invariant

Reputation: 8900

facade for a method that returns Promise in ScalaJS

I am writing facade for PouchDB Put Method

here is my facde

@JSName("PouchDB")
class PouchDB extends js.Object {
      type CALLBACK = js.Function2[js.UndefOr[js.Dynamic], js.UndefOr[js.Dynamic], Unit]

def this(name: js.UndefOr[String] = js.undefined, options: js.UndefOr[PouchDBOptions] = js.undefined) = this()

def put(doc: js.Object, docId: js.UndefOr[String] = js.undefined, docRev: js.UndefOr[String] = js.undefined, options: js.UndefOr[js.Object] = js.undefined, callback: CALLBACK = ???): Unit = js.native

...

put API takes a callback and also returns Promise , how can i define facade for put API which return promise..

Upvotes: 0

Views: 812

Answers (2)

Update a couple of years later ;-)

Scalajs contains a build-in type for a JS Promise, just use js.Promise[_].

See: https://www.scala-js.org/doc/interoperability/types.html

Upvotes: 2

sjrd
sjrd

Reputation: 22105

You will need a type for your Promises, just as for everything else. A promise is nothing magical, it's just an object with an interface, which you can type. You will need to know what's the API of PouchDB's promises, but it most likely is something (very) close to Promises/A+. In that case, it would look something like this:

import scala.scalajs.js
import js.annotation.JSName

trait Promise[+A] extends js.Object {
  @JSName("then")
  def andThen[B](onFulfilled: js.Function1[A, B],
      onRejected: js.Function1[Any, B]): Promise[B] = js.native

  @JSName("then")
  def andThen[B](onFulfilled: js.Function1[A, B]): Promise[B] = js.native

  @JSName("then")
  def andThen[B >: A](onFulfilled: Unit = (),
      onRejected: js.Function1[A, B] = ???)): Promise[B] = js.native
}

It's a bit convoluted because the an unspecified handler means that the promise returned by then can contain the same type of value as this promise if the onFulfilled handler is not specified. But I believe it should work like this.

Then you can declare put as returning a Promise[A] for some appropriate type A.

Upvotes: 2

Related Questions