为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript Promises:获取 .then 检索 [[PromiseValue]]

Javascript Promises:获取 .then 检索 [[PromiseValue]]

HUH函数 2023-01-06 10:55:26
我正在尝试检索[[PromiseValue]]Promise 的。我的函数当前返回一个 Promise,而我想要myFunction返回的值是存储在[[PromiseValue]]返回的 Promise 中的值。这将返回一个 Promise。myFunction(){    return fetch("/api")        .then(res => {            return res.json();        })        .then(json => {            return json;        })}我试过这段代码,但是当我在控制台中打印数据时,它打印出正确的值,但返回的值是未定义的。myFunction(){    return fetch("/api")        .then(res => {            return res.json();        })        .then(json => {            return json;        })        .then(data => {            const stringData = data.toString();            console.log(stringData); // prints the correct string            return stringData; // returns undefined        })}我如何让我的函数返回存储在[[PromiseValue]]字符串中的值?请帮帮我,谢谢!
查看完整描述

1 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

您的函数不能PromiseValue直接返回,因为fetch异步工作。它将返回一个Promise,最终将解析为该值。

使用async/await,你可以做的是:

async function myFunction() {

  const res = await fetch('/api');

  const json = await res.json();

  return JSON.stringify(json);

  // json.toString() is a bit weird … but do as you please

  // I'd return the json and parse it at the callsite.

}


const result = await myFunction();

(注意:这个片段需要一个支持顶级的现代引擎await。最新的 chrome 可以正常工作。)


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信