首页 > 解决方案 > JS Fetch API 访问返回值

问题描述

这就是我从 fetch 调用中访问结果的方式:

let data;

fetch(someUri)
    .then((response) => response.json())
    .then(_data => {
        data = _data;
    })
    .catch(error => {
        console.error(error);
    });

是否也可以从 fetch 函数本身访问结果,如下所示:

let data = fetch(someUri)
    .then((response) => response.json())
    .then(data => {
        // do some stuff
        return data;
    })
    .catch(error => {
        return error;
    });

dataJSON数据或错误也是如此。我在 Chrome 控制台中看到结果在变量中,但我不知道如何访问它,因为它包含其他信息。

标签: javascriptfetch

解决方案


您可以将其包装在立即调用的异步函数中并使用 await:

https://jsfiddle.net/ibowankenobi/ok72rfp6/

!async function(){
let data = await fetch("https://raw.githubusercontent.com/IbrahimTanyalcin/LEXICON/master/lexiconLogo.png")
    .then((response) => response.blob())
    .then(data => {
        return data;
    })
    .catch(error => {
        console.error(error);
    });

console.log(data);
}();

推荐阅读