同步获得已解决的Promise的价值 [英] Get value of resolved Promise in sync

查看:676
本文介绍了同步获得已解决的Promise的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们知道Promise确实可以解决,那么我们如何访问该值,如果不能,为什么不呢?

If we know that a Promise is definitely resolved, how can we access the value and if we can't, why not?

let a = Promise.resolve(123);

console.log(a.value); // ???

以下内容无效-打印"First,Last,123"

The following does not work- it prints "First, Last, 123"

console.log("First");
Promise.resolve(123).then(console.log);
console.log("Last");

我在问如何同步获取已经解析的Promise的值,如果那不可能,为什么不呢?

I'm asking how to get the value of an already resolved Promise synchronously and if that's not possible, why not?

推荐答案

否,无法执行此操作.这是设计使然.

No, it is not possible to do this. This is by design.

Promise A +规范旨在用作一种简单,一致的方式来处理异步操作.约束之一是,在已解决的Promise上将新的回调传递到then(),将始终在事件循环中的稍后时间执行 ,因此事情是一致的.

The Promise A+ specification is meant to be used as a simple, consistent way to deal with asynchronous operations. One of the constraints is that passing a new callback on to then() on an already resolved promise will always execute on a later tick in the event loop, so things are consistent.

添加第二种方法来检查承诺结果并非没有可能.这样做可能很容易,但是将其添加到规范中至少存在两个问题:

Adding a secondary way to inspect promise results would not have been impossible. It would probably have been quite easy to do so, but there's at least 2 problems with adding this to the specification:

  1. 如果您要构建规范,则希望它尽可能简单.规范本身实际上仅定义then()函数.
  2. 通过添加此功能,您为成群的开发人员打开了大门,使他们对已经难以理解的某些东西更加困惑.
  1. If you're looking to build a specification, you want it to be as simple as possible. The specification itself actually only defines the then() function.
  2. By adding this feature, you're opening the door to hordes of developers getting even more confused about something that's already hard to grok.

人们很难理解承诺和异步操作.我每天都在这里看到有关承诺而不是兑现"的问题.如果将访问承诺结果的非异步方式添加到默认承诺中,那么我想这将是一个更大的数目.尝试执行正确的做事方式"是很好的.

Promises and asynchronous operations are hard for people to understand. I see questions here daily about promises and not 'getting' it. If non-async way to access promise results would be added to the default promise, I'd imagine that this would be an even larger amount. It's good to try and enforce 'the right way' of doing things.

但是,此决定并非简单地为您做出.您没有被困在那里.您可以很容易地构建自己的具有此功能的诺言版本,并且仍然可以与现有诺言一起使用.只要您的对象具有根据Promises/A +行为的then()函数,您就可以随心所欲地处理其余对象.

However, this decision is not simply made for you. You're not stuck there. You can very easily build your own version of a promise that has this feature, and still works with existing promises. As long as your object has a then() function that behaves according to Promises/A+ you can do with the rest of the object whatever you want.

这篇关于同步获得已解决的Promise的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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