繁体   English   中英

Javascript 承诺:fetch.then 检索 [[PromiseValue]]

[英]Javascript Promises: fetch .then retrieving [[PromiseValue]]

我正在尝试检索 Promise 的[[PromiseValue]] 我的 function 当前返回 Promise 而我希望myFunction返回的值是存储在返回的 Promise 的[[PromiseValue]]中的值。

这将返回 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
        })
}

如何让我的 function 将存储在[[PromiseValue]]中的值作为字符串返回? 请帮帮我,谢谢!

您的 function 不能直接返回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 可以正常工作。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM