Skip to content

scalajs-io/mpromise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mpromise binding for Scala.js

mpromise - A promises/A+ conformant implementation, written for mongoose.

Description

A promises/A+ conformant implementation, written for mongoose.

Build Dependencies

Build/publish the SDK locally

 $ sbt clean publish-local

Running the tests

Before running the tests the first time, you must ensure the npm packages are installed:

$ npm install

Then you can run the tests:

$ sbt test

Examples

A simple example:

import io.scalajs.nodejs._
import io.scalajs.npm.mpromise._

val promise = new Promise[(Int, Int)]()
promise.onFulfill { case (a, b) =>
  Assert.equal(3, a + b)
}
promise.fulfill((1, 2))

Supports asynchronous execution pipelines:

import io.scalajs.nodejs._
import io.scalajs.npm.mpromise._

val promise = new Promise[Int]()
promise
    .`then`(arg => arg + 1)
    .`then`(arg => throw new Error(arg + " is an error!"))
    .`then`(null, { err =>
      Assert.ok(err.isInstanceOf[Error])
      Assert.equal("2 is an error", err.message)
})
promise.fulfill(1)

Supports conversion to Futures.

import io.scalajs.npm.mpromise._
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue

val promise = new Promise[(Int, Int)]()
promise.fulfill((2, 3))

promise.toFuture foreach { case (a, b) =>
  println(s"result: ${a + b}") // 5
}

Supports promise chaining:

import io.scalajs.npm.mpromise._
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue

def makeMeAPromise(i: Int) = {
    val p = new Promise[Int]()
    p.fulfill(i)
    p
}

val initialPromise = new Promise[Int]()
var returnPromise = initialPromise
for (i <- 0 until 10) {
  returnPromise = returnPromise.chain(makeMeAPromise(i))
}

initialPromise.fulfill(1)
returnPromise.toFuture foreach { result =>
  println(s"returnPromise: $result") // 9
}

Artifacts and Resolvers

To add the mpromise binding to your project, add the following to your build.sbt:

libraryDependencies += "io.scalajs.npm" %%% "mpromise" % "0.5.0"

Optionally, you may add the Sonatype Repository resolver:

resolvers += Resolver.sonatypeRepo("releases")