简体   繁体   English

异步函数返回一个承诺

[英]Async function returns a promise

I found an example on the web that looks like the following: 我在网上找到了一个如下所示的示例:

async function asyncFunc() {
    return Promise.resolve(123);
}
asyncFunc()
  .then(x => console.log(x)) // 123

However, I can also write it like that: 但是,我也可以这样写:

async function asyncFunc() {
    return 123
}
asyncFunc()
  .then(x => console.log(x)) // 123

I mean, I can find a use case for returning a resolved answer (for example, memoization/caching), But why should I actually use it if I can simply return the result, straightforward? 我的意思是,我可以找到一个用于返回已解决答案的用例(例如,记忆/缓存),但是如果我可以简单地直接返回结果,为什么我应该实际使用它呢?

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

When an async function is called, it returns a Promise. 调用异步函数时,它将返回一个Promise。 When the async function returns a value, the Promise will be resolved with the returned value. 当异步函数返回值时,Promise将使用返回的值进行解析。 When the async function throws an exception or some value, the Promise will be rejected with the thrown value. 当异步函数抛出异常或某个值时,Promise将被抛出的值拒绝。

Emphasis mine. 强调我的。

Both your examples are totally valid, although returning a resolved promise in the first case is unnecessary. 您的两个示例都是完全有效的,尽管在第一种情况下无需返回已解决的承诺。 Any async function that returns a plain value will wrap that value into a resolved promise automatically. 任何返回纯值的异步函数都会将该值自动包装为已解析的Promise。 I think typically people prefer the second example, as it's more straightforward. 我认为通常人们喜欢第二个例子,因为它更直接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM