如何获得承诺的价值?
我正在查看$ Q
的Angular文档中的示例,但我认为这可能适用于通常的承诺。下面的示例是从他们的文档中逐字复制的,其中包括:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1
我不清楚这是如何工作的。如果我可以在第一个的结果上调用
。然后()
。 >是类型对象
的承诺对象。它不是号码
。那么,“它的价值将是promisea逐渐增加1的结果”是什么意思?
我应该以PromiseB.Value
或类似的方式访问它吗?成功回调如何返回承诺并返回“结果 + 1”?我缺少一些东西。
I'm looking at this example from Angular's documentation for $q
, but I think this probably applies to promises in general. The example below is copied verbatim from their documentation with their comment included:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved and its value
// will be the result of promiseA incremented by 1
I'm not clear how this works. If I can call .then()
on the result of the first .then()
, chaining them, which I know I can, then promiseB
is a promise object, of type Object
. It is not a Number
. So what do they mean by "its value will be the result of promiseA incremented by 1"?
Am I supposed to access that as promiseB.value
or something like that? How can the success callback return a promise AND return "result + 1"? I'm missing something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
Promisea
's然后
函数返回一个新的Promise(Promiseb
),在解决Promisisea
之后,该函数立即解决,其已解决,值是从Promisea
中的成功函数返回的值的值。在这种情况下>。
访问
PromiseB
的值的方法是以相同的方式访问Promisea
的结果。从/
等待
是JavaScript中的标准上述方法的替代语法。您现在可以写:现在没有PromiseB,因为我们使用Promisea的结果使用了
等待
,您可以直接使用它。但是,
等待
只能在async
函数中使用。因此,要稍微缩小,上面的内容必须像这样包含:并且为了清楚地说,在此示例中,函数
dosomething
的返回值仍然是一个承诺 - 因为async functions返回承诺。因此,如果您想访问该返回值,则必须执行result =等待Dosomething()
,您只能在另一个异步函数中进行操作。基本上,只有在父级上下文中,您才能直接访问从儿童异步上下文中产生的值。promiseA
'sthen
function returns a new promise (promiseB
) that is immediately resolved afterpromiseA
is resolved, its value is the value of what is returned from the success function withinpromiseA
.In this case
promiseA
is resolved with a value -result
and then immediately resolvespromiseB
with the value ofresult + 1
.Accessing the value of
promiseB
is done in the same way we accessed the result ofpromiseA
.As of ECMAScript 2016 (ES7, 2016),
async
/await
is standard in JavaScript, which allows an alternative syntax to the approach described above. You can now write:Now there is no promiseB, because we've unwrapped the result from promiseA using
await
, and you can work with it directly.However,
await
can only be used inside anasync
function. So to zoom out slightly, the above would have to be contained like so:And, for clarity, the return value of the function
doSomething
in this example is still a promise - because async functions return promises. So if you wanted to access that return value, you would have to doresult = await doSomething()
, which you can only do inside another async function. Basically, only in a parent async context can you directly access the value produced from a child async context.当解决方案解决/拒绝时,它将调用其成功/错误处理程序:
然后
方法还返回承诺:PromiseB,将根据来自返回值的返回值解决/拒绝 Promisea 的成功/错误处理程序。Promisea的成功/错误处理程序可以返回三个可能的值,这将影响Promiseb的结果:
未定义的未定义将传递给Promistb的成功处理程序
该值将传递给PromiseB的成功处理程序
当被拒绝时,PromiseB将被拒绝。价值传递给
当时的Promiseb的处理程序将是武装这种理解的承诺的结果
,您可以理解以下内容:
然后立即呼叫返回Promiseb。
当解决Promisea时,结果将把结果传达给Promisea的成功处理程序。
由于返回值是Promisea的结果 + 1,因此成功处理程序正在返回一个值(上面的选项2),因此PromiseB将立即解决,PromiseB的成功处理程序将通过Promisisea的结果 + 1通过。
When a promise is resolved/rejected, it will call its success/error handler:
The
then
method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:
and undefined is passed to the success handler of promiseB
and the value is passed to the success handler of promiseB
When rejected, promiseB will be rejected. The value passed to
the promiseB's then handler will be the result of the promise
Armed with this understanding, you can make sense of the following:
The then call returns promiseB immediately.
When promiseA is resolved, it will pass the result to promiseA's success handler.
Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.
pixelbits的答案是正确的,而且,您应始终使用
。然后()
来访问生产代码中的承诺价值。但是,通过使用以下未支持的内部 node.js 绑定:
警告:process.tinding永远不会在node.js core和node.js核心团队正在积极寻求贬值
doc:doc: process.inding#22004
pixelbits' answer is correct, and you should always use
.then()
to access the value of a promise in production code.However, there is a way to access the promise's value directly after it has been resolved by using the following unsupported internal Node.js binding:
WARNING: process.binding was never meant to be used outside of Node.js core and the Node.js core team is actively looking to deprecate it
doc: documentation deprecation of process.binding #22004
Migration from process.binding #22064
以前有一些不错的答案,这是 es6> es6 版本:
There are some good previous answers and here is the ES6 arrow function version:
。
在这里,Promisea正在返回一个数字,该号码将以
number
参数为 success 的函数 的函数。然后将增加1。The
.then
function of promiseB receives what is returned from the.then
function of promiseA.Here promiseA is returning a number, which will be available as the
number
parameter in the success function of promiseB. Which will then be incremented by 1.实际上,从交互式(node.js)提示符中,一个人可以“等待”:
在 repl 。
您不能在“普通”函数中执行此操作:
您可以在“异步函数”中执行此操作,但是这会使您持希望,而不是您想要的价值:
Actually, from the interactive (Node.js) prompt, one can just "await":
This is useful when experimenting at the REPL.
You can't do this in an "ordinary" function:
You can do this in an "async function", but that leaves you back holding a promise, not the value you want:
对评论的解析与您当前的理解可能有所不同:
这说明
Promiseb
是一个承诺,但是在解决Promisea
后,它将立即解决。查看这种情况的另一种方法意味着promisea.then()
返回将分配给Promiseb
的承诺。这意味着
promisea
解决的值是Promiseb
将作为其成功的CORCECALLBACK值接收到的值:Parsing the comment a little differently than your current understanding might help:
This states that
promiseB
is a promise, but it will be resolved immediately afterpromiseA
is resolved. Another way of looking at this means thatpromiseA.then()
returns a promise that is assigned topromiseB
.This means that the value that
promiseA
resolved to is the value thatpromiseB
will receive as its successCallback value:我是JavaScript承诺的缓慢学习者。默认情况下,所有异步函数都会返回承诺,您可以将结果包裹为:
from 等待 ( mdn ):
更多地阅读有关等待和 promises /developer.mozilla.org/en-us/“ rel =” nofollow noreferrer“> mdn Web文档。
I am a slow learner of JavaScript promises. By default, all async functions return a promise, and you can wrap your result as:
From await (MDN):
Read more about await and promises at MDN web documentation.
在 repl ,获取一个是承诺价值的数据库连接,我采用了以下方法:
等待
的行通常会返回承诺。该代码可以粘贴到node.js repl,或者保存在 index.js 中。它可以以bash的速度运行,并在运行脚本访问设置变量后将您留在node.js depp中。为了确认异步函数已返回,您可以记录
Connection
,然后可以使用该变量。当然,一个不想依靠在异步函数之外的脚本中的任何代码解决的异步函数。In the Node.js REPL, to get a database connection that was the value of a promise, I took the following approach:
The line with
await
would normally return a promise. This code can be pasted into the Node.js REPL or if saved in index.js. it can be run in Bash withwhich leaves you in the Node.js REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log
connection
for example, and then you're ready to use the variable. One of course wouldn't want to count on the asynchronous function being resolved yet for any code in the script outside the asynchronous function.从而访问了承诺的值
在交互提示进行实验时,可以通过将值分配给“ then()”函数中的全局变量,例如:在代码中,这个想法似乎总是强迫一个人来放置一个“函数”, 。跟进“代码”中的“ then()”部分(或等效地,如果我理解的话,将异步/等待模式添加到“同样”中,如果我理解,它将被重写为“ then then()”模式。我想的想法是,这可以防止“阻止”系统,尽管在我看来,没有提供任何后门来同步获得该价值,这似乎是语言设计师的家长式化。
请注意,再次从交互式命令行:
这是因为“ then()” 中的代码尚未运行。
但是,在“下一行”(在交互式提示下)可以做:
When experimenting at an interactive prompt, one can access the value of a Promise by assigning the value to a global variable in the "then()" function, e.g.:
In code, the idea seems to be to always force one to put the "follow up" code into the "then()" part (or, equivalently, if I understand, into the async/await pattern, which, again if I understand, gets rewritten into the "then()" pattern). I suppose the idea is that this prevents "blocking" the system, although providing no backdoor to get the value synchronously seems to me to be excessively paternalistic of the language designers.
Note, again from the interactive command line:
This is because the code in the "then()" has not run yet.
However, on the "next line" (at the interactive prompt) one can do:
mdn 文档帮助我解决了这个问题:
”需要降低JSON对象的多个级别:
The MDN documentation helped me resolve this issue:
Promise.resolve()
If you need to need to go down multiple levels of the JSON object:
这个示例我发现不言自明。请注意等待结果如何等待结果,因此您错过了退回的承诺。
This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.
您可以在JavaScript中使用异步等待方法轻松地做到这一点。
以下是一个示例,检索a webrtc 使用超时使用超时。
You can easily do that using an async wait method in JavaScript.
Below is an example retrieving a WebRTC promise value using a timeout.