本文介绍了如何访问承诺的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看 $q Angular 文档中的这个示例,但我认为这可能适用于一般的承诺.下面的示例是从他们的文档中逐字复制的,其中包括他们的评论:

I'm looking at this example from Angular's docs for $q but I think this probably applies to promises in general. The example below is copied verbatim from their docs 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

我不清楚这是如何工作的.如果我可以在第一个 .then() 的结果上调用 .then(),链接它们,我知道我可以,然后 promiseB 是一个承诺对象,类型为 Object.它不是 Number.那么他们所说的它的值将是 promiseA 加 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"?

我应该以 promiseB.value 或类似的方式访问它吗?成功回调如何返回承诺并返回结果 + 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.

推荐答案

promiseAthen 函数返回一个新的 promise (promiseB)promiseA 解析后立即解析,其值是 promiseA 中成功函数返回的值.

promiseA's then function returns a new promise (promiseB) that is immediately resolved after promiseA is resolved, its value is the value of the what is returned from the success function within promiseA.

在这种情况下,promiseA 用一个值 - result 解析,然后立即用 result + 1 的值解析 promiseB.

In this case promiseA is resolved with a value - result and then immediately resolves promiseB with the value of result + 1.

访问promiseB的值与访问promiseA的结果相同.

Accessing the value of promiseB is done in the same way we accessed the result of promiseA.

promiseB.then(function(result) {
    // here you can use the result of promiseB
});

Edit December 2019:async/await 现在是 JS 中的标准,它允许上述方法的替代语法.你现在可以写:


Edit December 2019: async/await is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:

let result = await functionThatReturnsPromiseA();
result = result + 1;

现在没有 promiseB,因为我们已经使用 await 对 promiseA 的结果进行了解包,您可以直接使用它.

Now there is no promiseB, because we've unwrapped the result from promiseA using await, and you can work with it directly.

然而,await 只能在 async 函数内使用.所以要稍微缩小,上面的内容必须像这样:

However, await can only be used inside an async function. So to zoom out slightly, the above would have to be contained like so:

async function doSomething() {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}

这篇关于如何访问承诺的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:11