Javascript承诺:先提取然后检索[[PromiseValue]]

问题描述

我正在尝试检索Promise的[[PromiseValue]]。 我的函数当前返回一个Promise,我要myFunction返回的值是存储在返回的Promise的[[PromiseValue]]中的值。

这将返回一个承诺。

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]]中的值? 请帮帮我,谢谢!

解决方法

您的函数无法直接返回A * B * C,因为PromiseValue是异步工作的。它将返回Promise,最终将解析为该值。

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

fetch

(注意:此代码段需要一个支持顶级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(); 的现代引擎。最新的chrome可以正常使用。)