异步/等待总是返回promise [英] async/await always returns promise

查看:146
本文介绍了异步/等待总是返回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;
}

当我以这种方式使用代码

When I use the code in this way

console.log(getJSON()); // returns 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 resolves or rejects.

所以不,即使使用await,也不能直接对异步函数的结果执行console.log.使用await将使您的函数等待,然后返回立即解析的Promise,但不会为您解包Promise.您仍然需要使用await.then()解开async函数返回的Promise.

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的 outside 中获得Promise的结果.这是与Promises合作的模型的一部分.

When you use .then() instead of console.logging 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.

这篇关于异步/等待总是返回promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆