为什么Promise没有get()函数? [英] Why does Promise not have a get() function?

查看:79
本文介绍了为什么Promise没有get()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您知道Promise已经解决了,为什么不能只在它上面调用 get()并收到值?而不是使用然后使用回调函数(..)

If you know that the Promise has already been resolved why can't you just call get() on it and receive the value? As opposed to using then(..) with a callback function.

所以不要这样做:

promise.then(function(value) {
  // do something with value
});

我希望能够做得更简单:

I want to be able to do the much simpler:

var value = promise.get();

Java为它提供了这个 CompletableFuture ,我认为没有理由不能提供相同的JavaScript。

Java offers this for it's CompletableFuture and I see no reason why JavaScript couldn't offer the same.

推荐答案

Java的获取方法如有必要,等待此未来完成,即它阻止当前线程。我们绝对不想在只有一个线程的JavaScript中这样做。

Java's get method "Waits if necessary for this future to complete", i.e. it blocks the current thread. We absolutely never want to do that in JavaScript, which has only one "thread".

可以将API中的方法集成到同步确定是否以及履行承诺的结果,但是他们没有做到这一点是件好事。只有一个方法然后,以便在可用时获得结果,使事情变得更容易,更安全,更一致。编写自己的if-pending-then-else-else-that逻辑没有任何好处,它只会为错误提供可能性。异步很难。

It would have been possible to integrate methods in the API to determine synchronously whether and with what results the promise completed, but it's a good thing they didn't. Having only one single method, then, to get results when they are available, makes things a lot easier, safer and more consistent. There's no benefit in writing your own if-pending-then-this-else-that logic, it only opens up possibilities for mistakes. Asynchrony is hard.

这篇关于为什么Promise没有get()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆