异步/等待总是返回promise

编程入门 行业动态 更新时间:2024-10-19 17:19:59
本文介绍了异步/等待总是返回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

本文发布于:2023-11-08 20:27:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!