简体   繁体   English

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

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

I'm trying to retrieve the [[PromiseValue]] of a Promise.我正在尝试检索 Promise 的[[PromiseValue]] My function currently returns a Promise instead and the value I want myFunction to return is the value stored in [[PromiseValue]] of the returned Promise.我的 function 当前返回 Promise 而我希望myFunction返回的值是存储在返回的 Promise 的[[PromiseValue]]中的值。

This returns a Promise.这将返回 Promise。

myFunction(){
    return fetch("/api")
        .then(res => {
            return res.json();
        })
        .then(json => {
            return json;
        })
}

I tried this code, but when I print the data in console, it prints the correct value, but the returned value is undefined.我尝试了这段代码,但是当我在控制台中打印数据时,它会打印正确的值,但返回的值是未定义的。

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
        })
}

How would I make my function return the value stored in [[PromiseValue]] as a String?如何让我的 function 将存储在[[PromiseValue]]中的值作为字符串返回? Please help me out, thanks!请帮帮我,谢谢!

Your function cannot return the PromiseValue directly, since fetch works asynchronously.您的 function 不能直接返回PromiseValue ,因为fetch是异步工作的。 It will return a Promise which will eventually resolve to that value.它将返回一个Promise最终将解析为该值。

Using async/await , what you could do is:使用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();

(note: this snippet requires a modern engine which supports top-level await . Latest chrome will work just fine.) (注意:这个片段需要一个支持顶级await的现代引擎。最新的 chrome 可以正常工作。)

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

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