Javascript 如何访问承诺的价值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29516390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:30:16  来源:igfitidea点击:

How to access the value of a promise?

javascriptangularjspromiseangular-promise

提问by temporary_user_name

I'm looking at this example from Angular's docs for $qbut I think this probably applies to promises in general. The example below is copied verbatim from their docs with their comment included:

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

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 promiseBis 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"?

我不清楚这是如何工作的。如果我可以调用.then()第一个的结果,将.then()它们链接起来,我知道我可以,那么promiseB就是一个 promise 对象,类型为Object。它不是一个Number. 那么他们所说的“它的值将是 promiseA 加 1 的结果”是什么意思?

Am I supposed to access that as promiseB.valueor something like that? How can the success callback return a promise AND return "result + 1"? I'm missing something.

我应该promiseB.value像那样访问它还是类似的东西?成功回调如何返回承诺并返回“结果 + 1”?我错过了一些东西。

采纳答案by Nachshon Schwartz

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

promiseAthen函数返回一个新的promise( promiseB),它在resolved后立即promiseA被resolved,它的值是success函数返回的值promiseA

In this case promiseAis resolved with a value - resultand then immediately resolves promiseBwith the value of result + 1.

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

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

访问 的值的promiseB方式与访问 的结果相同promiseA

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


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

2019 年 12 月编辑async/await现在是 JS 的标准,它允许上述方法的替代语法。你现在可以写:

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

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

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

However, awaitcan only be used inside an asyncfunction. So to zoom out slightly, the above would have to be contained like so:

但是,await只能在async函数内部使用。因此,要稍微缩小,必须像这样包含上述内容:

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

回答by pixelbits

When a promise is resolved/rejected, it will call its success/error handler:

当承诺被解决/拒绝时,它将调用其成功/错误处理程序:

var promiseB = promiseA.then(function(result) {
   // do something with result
});

The thenmethod also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

then方法还返回一个promise:promiseB,它将根据promiseA 的成功/错误处理程序的返回值来解决/拒绝。

There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

promiseA 的成功/错误处理程序可以返回三个可能的值,这些值会影响 promiseB 的结果:

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   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:

有了这种理解,您可以理解以下内容:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

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.

then 调用立即返回 promiseB。当 promiseA 被解析时,它会将结果传递给 promiseA 的成功处理程序。由于返回值是 promiseA 的结果 + 1,成功处理程序正在返回一个值(上面的选项 2),因此 promiseB 将立即解析,并且 promiseB 的成功处理程序将传递 promiseA 的结果 + 1。

回答by harishr

.thenfunction of promiseB receives what is returned from .thenfunction of promiseA.

.thenpromiseB 的函数接收从.thenpromiseA 函数返回的内容。

here promiseA is returning is a number, which will be available as numberparameter in success function of promiseB. which will then be incremented by 1

这里promiseA 返回的是一个数字,它将作为numberpromiseB 的成功函数中的参数可用。然后将增加 1

回答by Jason Cust

Parsing the comment a little differently than your current understanding might help:

以与您目前的理解略有不同的方式解析评论可能会有所帮助:

// promiseB will be resolved immediately after promiseA is resolved

This states that promiseBis a promise but will be resolved immediately after promiseAis resolved. Another way of looking at this means that promiseA.then()returns a promise that is assigned to promiseB.

这表明这promiseB是一个承诺,但将在解决后立即promiseA解决。从另一种角度来看,这意味着promiseA.then()返回分配给promiseB.

// and its value will be the result of promiseA incremented by 1

This means that the value that promiseAresolved to is the value that promiseBwill receive as its successCallback value:

这意味着promiseA解析为的值是promiseB将作为其 successCallback 值接收的值:

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});

回答by Zeus Lalkaka

pixelbits answer is correct and you should always use .then()to access the value of a promise in production code.

pixelbits 答案是正确的,您应该始终使用它.then()来访问生产代码中承诺的值。

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:

但是,有一种方法可以在使用以下不受支持的内部 node.js 绑定解析后直接访问 promise 的值:

process.binding('util').getPromiseDetails(myPromise)[1]

WARNING: process.binding was never meant to be used outside of nodejs core and the nodejs core team is actively looking to deprecate it

警告:process.binding 从未打算在 nodejs 核心之外使用,并且 nodejs 核心团队正在积极寻求弃用它

https://github.com/nodejs/node/pull/22004https://github.com/nodejs/node/issues/22064

https://github.com/nodejs/node/pull/22004 https://github.com/nodejs/node/issues/22064

回答by Master James

This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.

这个例子我觉得不言自明。请注意 await 如何等待结果,因此您错过了返回的 Promise。

cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise?{<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}

回答by dmstack

In the Node REPL, to get a DB connection that was the value of a promise, I took the following approach:

在 Node REPL 中,为了获得作为承诺值的数据库连接,我采用了以下方法:

let connection
try {
  (async () => {
    connection = await returnsAPromiseResolvingToConnection()
  })()
} catch(err) {
  console.log(err)
}

The line with awaitwould normally return a promise. This code can be pasted into the Node REPL or if saved in index.jsit can be run in Bash with

await通常会返回一个承诺。此代码可以粘贴到节点 REPL 中,或者如果保存在index.js其中可以在 Bash 中运行

node -i -e "$(< index.js)"

which leaves you in the Node REPL after running the script with access to the set variable. To confirm that the asynchronous function has returned, you can log connectionfor 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.

在运行脚本并访问 set 变量后,它会将您留在节点 REPL 中。例如,要确认异步函数已返回,您可以登录connection,然后就可以使用该变量了。当然,对于异步函数之外的脚本中的任何代码,人们当然不想指望正在解析异步函数。

回答by roopa l

There are some good answer above and here is the ES6 Arrow function version

上面有一些很好的答案,这里是 ES6 箭头函数版本

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;
}

回答by tomnyson

promiseA(pram).then(
     result => { 
     //make sure promiseA function allready success and response
     //do something here
}).catch(err => console.log(err)) => {
     // handle error with try catch
}

回答by OxFEEDFACE

You can easily do that using an async wait method in javascript.

您可以使用 javascript 中的异步等待方法轻​​松做到这一点。

Below is an example retrieving a WebRTC promise value using a timeout.

下面是使用超时检索 WebRTC 承诺值的示例。

function await_getipv4(timeout = 1000) {
    var t1 = new Date();
    while(!window.ipv4) {
        var stop = new Date() - t1 >= timeout;
        if(stop) {
            console.error('timeout exceeded for await_getipv4.');
            return false;
        }
    }
    return window.ipv4;
}

function async_getipv4() {
    var ipv4 = null;
    var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
    findIP.then(ip => window.ipv4 = ip);
    return await_getipv4();
};