首页 > 解决方案 > Javascript Promises:获取 .then 检索 [[PromiseValue]]

问题描述

我正在尝试检索[[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]]作为字符串存储的值?请帮帮我,谢谢!

标签: javascriptreactjspromisefetchrequest-promise

解决方案


您的函数不能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 可以正常工作。)


推荐阅读