如何获得承诺的价值?

发布于 2025-02-13 00:19:41 字数 543 浏览 0 评论 0原文

我正在查看$ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

回首观望 2025-02-20 00:19:41

Promisea's 然后函数返回一个新的Promise(Promiseb),在解决Promisisea之后,该函数立即解决,其已解决,值是从Promisea中的成功函数返回的值的值。

在这种情况下>。

访问PromiseB的值的方法是以相同的方式访问Promisea的结果。

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

/等待是JavaScript中的标准上述方法的替代语法。您现在可以写:

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

现在没有PromiseB,因为我们使用Promisea的结果使用了等待,您可以直接使用它。

但是,等待只能在async函数中使用。因此,要稍微缩小,上面的内容必须像这样包含:

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

并且为了清楚地说,在此示例中,函数dosomething的返回值仍然是一个承诺 - 因为async functions返回承诺。因此,如果您想访问该返回值,则必须执行result =等待Dosomething(),您只能在另一个异步函数中进行操作。基本上,只有在父级上下文中,您才能直接访问从儿童异步上下文中产生的值。

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

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

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
});

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:

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.

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;
}

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 do result = 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.

不必了 2025-02-20 00:19:41

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

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

然后方法还返回承诺:PromiseB,将根据来自返回值的返回值解决/拒绝 Promisea 的成功/错误处理程序。

Promisea的成功/错误处理程序可以返回三个可能的值,这将影响Promiseb的结果:

  1. 返回什么都没有→PromiseB立即解决,
    未定义的未定义将传递给Promistb的成功处理程序
  2. 返回值→PromiseB立即解决,
    该值将传递给PromiseB的成功处理程序
  3. 返回承诺→解决后,PromiseB将得到解决。
    当被拒绝时,PromiseB将被拒绝。价值传递给
    当时的Promiseb的处理程序将是武装这种理解的承诺的结果

,您可以理解以下内容:

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

然后立即呼叫返回Promiseb。

当解决Promisea时,结果将把结果传达给Promisea的成功处理程序。

由于返回值是Promisea的结果 + 1,因此成功处理程序正在返回一个值(上面的选项2),因此PromiseB将立即解决,PromiseB的成功处理程序将通过Promisisea的结果 + 1通过。

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

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

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:

  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.

笑脸一如从前 2025-02-20 00:19:41

pixelbits的答案是正确的,而且,您应始终使用。然后()来访问生产代码中的承诺价值。

但是,通过使用以下未支持的内部 node.js 绑定:

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

警告:process.tinding永远不会在node.js core和node.js核心团队正在积极寻求贬值

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:

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

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

捶死心动 2025-02-20 00:19:41

以前有一些不错的答案,这是 es6> es6 版本:

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

There are some good previous answers and here is the ES6 arrow function version:

var something = async() => {
    let result = await functionThatReturnsPromiseA();
    return result + 1;
}
峩卟喜欢 2025-02-20 00:19:41

在这里,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.

梦中的蝴蝶 2025-02-20 00:19:41

实际上,从交互式(node.js)提示符中,一个人可以“等待”:

> y = new Promise((resolve, reject) => resolve(23));
Promise {
   23,
   [Symbol(async_id_symbol)]: 10419,
   [Symbol(trigger_async_id_symbol)]: 5,
   [Symbol(destroyed)]: { destroyed: false }
}
> v = await y;
23

repl

您不能在“普通”函数中执行此操作:

> function foo() { let z = await y; return z; }
Uncaught SyntaxError:
Unexpected token 'y'

您可以在“异步函数”中执行此操作,但是这会使您持希望,而不是您想要的价值:

> async function foo() { let z = await y; return z; }
undefined
> foo()
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 10571,
  [Symbol(trigger_async_id_symbol)]: 5,
  [Symbol(destroyed)]: { destroyed: false }
}

Actually, from the interactive (Node.js) prompt, one can just "await":

> y = new Promise((resolve, reject) => resolve(23));
Promise {
   23,
   [Symbol(async_id_symbol)]: 10419,
   [Symbol(trigger_async_id_symbol)]: 5,
   [Symbol(destroyed)]: { destroyed: false }
}
> v = await y;
23

This is useful when experimenting at the REPL.

You can't do this in an "ordinary" function:

> function foo() { let z = await y; return z; }
Uncaught SyntaxError:
Unexpected token 'y'

You can do this in an "async function", but that leaves you back holding a promise, not the value you want:

> async function foo() { let z = await y; return z; }
undefined
> foo()
Promise {
  <pending>,
  [Symbol(async_id_symbol)]: 10571,
  [Symbol(trigger_async_id_symbol)]: 5,
  [Symbol(destroyed)]: { destroyed: false }
}
﹎☆浅夏丿初晴 2025-02-20 00:19:41

对评论的解析与您当前的理解可能有所不同:

// promiseB will be resolved immediately after promiseA is resolved

这说明Promiseb是一个承诺,但是在解决Promisea后,它将立即解决。查看这种情况的另一种方法意味着promisea.then()返回将分配给Promiseb的承诺。

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

这意味着promisea解决的值是Promiseb将作为其成功的CORCECALLBACK值接收到的值:

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

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

// promiseB will be resolved immediately after promiseA is resolved

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

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

This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});
风吹过旳痕迹 2025-02-20 00:19:41

我是JavaScript承诺的缓慢学习者。默认情况下,所有异步函数都会返回承诺,您可以将结果包裹为:

(async () => {
//Optional "await"
  await yourAsyncFunctionOrPromise()
    .then(function (result) {
      return result +1;
    })
    .catch(function (error) {
      return error;
    })()
})

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:

(async () => {
//Optional "await"
  await yourAsyncFunctionOrPromise()
    .then(function (result) {
      return result +1;
    })
    .catch(function (error) {
      return error;
    })()
})

From await (MDN):

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfilment. When resumed, the value of the await expression is that of the fulfilled Promise.

If the Promise is rejected, the await expression throws the rejected value

Read more about await and promises at MDN web documentation.

写下不归期 2025-02-20 00:19:41

repl ,获取一个是承诺价值的数据库连接,我采用了以下方法:

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

等待的行通常会返回承诺。该代码可以粘贴到node.js repl,或者保存在 index.js 中。它可以以bash的速度运行,

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

并在运行脚本访问设置变量后将您留在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:

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

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 with

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

which 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.

×眷恋的温暖 2025-02-20 00:19:41

从而访问了承诺的值

> promise = new Promise((resolve, reject) => resolve(17));
Promise {
   17,
   [Symbol(async_id_symbol)]: 7600,
   [Symbol(trigger_async_id_symbol)]: 5,
   [Symbol(destroyed)]: { destroyed: false }
}
> global_cheat = null;
null
> promise.then((v) => { global_cheat = v; } );
Promise {
   <pending>,
  [Symbol(async_id_symbol)]: 7875,
  [Symbol(trigger_async_id_symbol)]: 7600,
  [Symbol(destroyed)]: { destroyed: false }
}
> global_cheat
17

在交互提示进行实验时,可以通过将值分配给“ then()”函数中的全局变量,例如:在代码中,这个想法似乎总是强迫一个人来放置一个“函数”, 。跟进“代码”中的“ then()”部分(或等效地,如果我理解的话,将异步/等待模式添加到“同样”中,如果我理解,它将被重写为“ then then()”模式。我想的想法是,这可以防止“阻止”系统,尽管在我看来,没有提供任何后门来同步获得该价值,这似乎是语言设计师的家长式化。

请注意,再次从交互式命令行:

> xyz=null; promise.then((v) => {xyz = v;}); console.log(`xyz=${xyz}`);
xyz=null

这是因为“ then()” 中的代码尚未运行。

但是,在“下一行”(在交互式提示下)可以做:

> xyz
17

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.:

> promise = new Promise((resolve, reject) => resolve(17));
Promise {
   17,
   [Symbol(async_id_symbol)]: 7600,
   [Symbol(trigger_async_id_symbol)]: 5,
   [Symbol(destroyed)]: { destroyed: false }
}
> global_cheat = null;
null
> promise.then((v) => { global_cheat = v; } );
Promise {
   <pending>,
  [Symbol(async_id_symbol)]: 7875,
  [Symbol(trigger_async_id_symbol)]: 7600,
  [Symbol(destroyed)]: { destroyed: false }
}
> global_cheat
17

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:

> xyz=null; promise.then((v) => {xyz = v;}); console.log(`xyz=${xyz}`);
xyz=null

This is because the code in the "then()" has not run yet.

However, on the "next line" (at the interactive prompt) one can do:

> xyz
17
策马西风 2025-02-20 00:19:41

mdn 文档帮助我解决了这个问题:

let promiseB = promiseA;

promiseB.then((value) => {
    console.log(value);
});

”需要降低JSON对象的多个级别:

let promiseB = promiseA;

promiseB.then((value) => {
    console.log(value?.key1.key2);
});

The MDN documentation helped me resolve this issue:

Promise.resolve()

let promiseB = promiseA;

promiseB.then((value) => {
    console.log(value);
});

If you need to need to go down multiple levels of the JSON object:

let promiseB = promiseA;

promiseB.then((value) => {
    console.log(value?.key1.key2);
});
魔法少女 2025-02-20 00:19:41
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
}
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
}
你的呼吸 2025-02-20 00:19:41

这个示例我发现不言自明。请注意等待结果如何等待结果,因此您错过了退回的承诺。

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}

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

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}
蓝梦月影 2025-02-20 00:19:41

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

以下是一个示例,检索a 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();
};

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

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

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();
};

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文