我在网上找到了一个示例,如下所示:
async function asyncFunc() {
return Promise.resolve(123);
}
asyncFunc()
.then(x => console.log(x)) // 123
但是,我也可以这样写:
async function asyncFunc() {
return 123
}
asyncFunc()
.then(x => console.log(x)) // 123
我的意思是,我可以找到一个返回已解决答案的用例(例如,内存/缓存),但是如果我可以直接简单地返回结果,为什么我应该实际使用它呢?
最佳答案
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function :
When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.
强调我的。
您的两个示例都是完全有效的,尽管在第一种情况下返回已解决的 promise 是不必要的。任何返回普通值的异步函数都会自动将该值包装到已解析的 Promise 中。我认为人们通常更喜欢第二个示例,因为它更简单。
关于javascript - 异步函数返回一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47402523/