JS Fetch API access return value [duplicate]

╄→尐↘猪︶ㄣ 提交于 2021-02-17 22:11:30

问题


This is how I access the result from a fetch call:

let data;

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

Is it also possible to access the result from the fetch function itself, like this:

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

So data will be either the JSON data or the error. I see in my Chrome console that the result is in the variable, but I don't know how to access it because it's wrapped with other information.


回答1:


You can wrap it inside an immediately invoked async function and use 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);
}();



回答2:


Here are some good resources for fetch and an example.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/API/Body/text https://developer.mozilla.org/en-US/docs/Web/API/Body/json

You may also want to get familiar with promises. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

 
    function doSomethingWithText(text) {
        console.log('The text is:', text);
    }

    fetch('someUrl.html')
      .then(data => data.text())
      .then(text => (doSomethingWithText(text))
      .catch(error => new Error(error));



回答3:


fetch method returns a promise that resolves to a Response object.

Once you get the response, it is up to you what to do with it. You can use methods on response body like json, text or blob to get data into desired format to work with.



来源:https://stackoverflow.com/questions/50417982/js-fetch-api-access-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!