async/await 总是返回承诺 [英] async/await always returns promise
问题描述
我正在尝试异步/等待功能.我有这样的代码模仿请求:
I'm trying async/await functionality. I have such code imitating a request:
const getJSON = async () => {
const request = () => new Promise((resolve, reject) => (
setTimeout(() => resolve({ foo: 'bar'}), 2000)
));
const json = await request();
return json;
}
当我这样使用代码时
console.log(getJSON()); // returns Promise
它返回一个 Promise
it returns a Promise
但是当我调用这行代码时
but when I call this line of code
getJSON().then(json => console.log(json)); // prints { foo: 'bar' }
它按预期打印 json
it prints json as expected
是否可以只使用像 console.log(getJSON())
这样的代码?我不明白什么?
Is it possible to use just code like console.log(getJSON())
? What don't I understand?
推荐答案
每个 async
函数都返回一个 Promise
对象.await
语句对 Promise
进行操作,等待直到 Promise
resolve
s 或 reject
>s.
Every async
function returns a Promise
object. The await
statement operates on a Promise
, waiting until the Promise
resolve
s or reject
s.
所以不,您不能直接对异步函数的结果执行 console.log
,即使您使用 await
.使用 await
将使您的函数等待,然后返回一个立即解析的 Promise
,但它不会为您打开 Promise
.您仍然需要解开 async
函数返回的 Promise
,使用 await
或使用 .then()
.
So no, you can't do console.log
on the result of an async function directly, even if you use await
. Using await
will make your function wait and then return a Promise
which resolves immediately, but it won't unwrap the Promise
for you. You still need to unwrap the Promise
returned by the async
function, either using await
or using .then()
.
当您直接使用 .then()
而不是 console.log
ging 时,.then()
方法使结果承诺提供给你.但是你不能从Promise的外部得到Promise
的结果.这是使用 Promise 的模型的一部分.
When you use .then()
instead of console.log
ging directly, the .then()
method makes the result of the Promise available to you. But you can't get the result of the Promise
from outside the Promise. That's part of the model of working with Promises.
这篇关于async/await 总是返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!