Nashorn和Scala未来向JS Promise转换
2022-09-01 04:00:06
我将尝试回答Scala Future to JS Promise的部分问题。由于您没有提供示例。我将在这里提供一个转换。如果我们说我们在Scala中以这种方式实现了未来:
val f: Future = Future {
session.getX()
}
f onComplete {
case Success(data) => println(data)
case Failure(t) => println(t.getMessage)
}
那么 JavaScript/ES6 中的相应代码可能如下所示:
var f = new Promise(function(resolve, reject) {
session.getX();
});
f.then((data) => {
console.log(data);
}).catch((t) => {
console.log(t);
}));
我知道这不是Scala,但我想把它包括在内以保持完整性。这是从Scala.js文档中获取的映射:Future
Promise
+-----------------------------------+------------------------+-------------------------------------------------------------------------------------------------------+
| Future | Promise | Notes |
+-----------------------------------+------------------------+-------------------------------------------------------------------------------------------------------+
| foreach(func) | then(func) | Executes func for its side-effects when the future completes. |
| map(func) | then(func) | The result of func is wrapped in a new future. |
| flatMap(func) | then(func) | func must return a future. |
| recover(func) | catch(func) | Handles an error. The result of func is wrapped in a new future. |
| recoverWith(func) | catch(func) | Handles an error. func must return a future. |
| filter(predicate) | N/A | Creates a new future by filtering the value of the current future with a predicate. |
| zip(that) | N/A | Zips the values of this and that future, and creates a new future holding the tuple of their results. |
| Future.successful(value) | Promise.resolve(value) | Returns a successful future containing value |
| Future.failed(exception) | Promise.reject(value) | Returns a failed future containing exception |
| Future.sequence(iterable) | Promise.all(iterable) | Returns a future that completes when all of the futures in the iterable argument have been completed. |
| Future.firstCompletedOf(iterable) | Promise.race(iterable) | Returns a future that completes as soon as one of the futures in the iterable completes. |
+-----------------------------------+------------------------+-------------------------------------------------------------------------------------------------------+